求預測值和真實值的誤差平方和,並使其達到最小
初始化θ0和θ1,不斷改變θ0和θ1,直到J(θ0,θ1)達到一個全域性最小值或者區域性最小值
α為學習率
一元線性迴歸方程
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt("../data/csv/data.csv", delimiter=",")
x_data = data[:, 0, np.newaxis]
y_data = data[:, 1, np.newaxis]
model = LinearRegression()
model.fit(x_data, y_data)
# 畫圖
plt.plot(x_data, y_data, 'b.')
plt.plot(x_data, model.predict(x_data), 'r')
plt.show()
x0=1,為了描述方便,讓x的下標與θ下標一一對應
多元線性迴歸方程
import numpy as np
from numpy import genfromtxt
from sklearn import linear_model
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 匯入資料
data = genfromtxt(r'E:/project/python/data/csv/Delivery.csv', delimiter=',')
# 切分資料
x_data = data[:, :-1]
y_data = data[:, -1]
# 建立模型
model = linear_model.LinearRegression()
model.fit(x_data, y_data)
print("係數:", model.coef_)
print("截距:", model.intercept_)
# 畫圖
ax = plt.figure().add_subplot(111, projection='3d')
ax.scatter(x_data[:, 0], x_data[:, 1], y_data, c='r', marker='o', s=100)
x0 = x_data[:, 0]
x1 = x_data[:, 1]
x0, x1 = np.meshgrid(x0, x1)
z = model.intercept_ + x0 * model.coef_[0] + x1 * model.coef_[1]
ax.plot_surface(x0, x1, z)
ax.set_xlabel('Miles')
ax.set_ylabel('Num of Deliveries')
ax.set_zlabel('Time')
plt.show()
本作品採用《CC 協議》,轉載必須註明作者和本文連結