<>梯度下降法实现多元线性回归（代码实现）

data = genfromtxt(r"\Delivery.csv", delimiter=',')

x_data为特征值，y_data为标签值

lr = 0.0001 # 参数 theta0 = 0 theta1 = 0 theta2 = 0 # 最大迭代次数 epochs = 1000

def compute_error(theta0, theta1, theta2, x_data, y_data): totalError = 0 for i
in range(0, len(x_data)): totalError += (y_data[i] - (theta1 * x_data[i, 0] +
theta2* x_data[i, 1] + theta0)) ** 2 return totalError / float(len(x_data)) def
gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr, epochs): #

theta1_grad= 0 theta2_grad = 0 # 计算梯度的总和再求平均 for j in range(0, len(x_data)):
theta0_grad+= -(1/m) * (y_data[j] - (theta1 * x_data[j, 0] + theta2*x_data[j, 1]
+ theta0)) theta1_grad += -(1 / m) * x_data[j, 0] * (y_data[j] - (theta1 *
x_data[j, 0] + theta2 * x_data[j, 1] + theta0)) theta2_grad += -(1 / m) * x_data
[j, 1] * (y_data[j] - (theta1 * x_data[j, 0] + theta2 * x_data[j, 1] + theta0))
theta2= theta2 - (lr*theta2_grad) return theta0, theta1, theta2 theta0, theta1,
theta2= gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr,
epochs)

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 = theta0 + x0 * theta1 +
theta2# 画3D图 ax.plot_surface(x0, x1, z) # 设置坐标轴 ax.set_xlabel('Miles') ax.
set_ylabel('Num of Deliveries') ax.set_zlabel('Time') plt.show()

<>用sklearn实现多元线性回归

model = linear_model.LinearRegression() model.fit(x_data, y_data)

# 系数 print('coefficients:', model.coef_) # 截距 print('intercept:', model.
intercept_)

x_test = [[10, 45]] predict = model.predict(x_test) print('predict:', predict)

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] # 画3D图 ax.plot_surface(x0, x1, z) # 设置坐标轴 ax.
set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()