赞
踩
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(0)
X1 = 2 * np.random.rand(100, 1)
X2 = 3 * np.random.rand(100, 1)
X3 = 4 * np.random.rand(100, 1)
y = 4 + 3 * X1 + 5 * X2 + 2 * X3 + np.random.randn(100, 1)
# 合并特征
X_b = np.hstack([np.ones((100, 1)), X1, X2, X3])
# 梯度下降求解多元线性回归系数
eta = 0.1 # 学习率
n_iterations = 1000 # 迭代次数
m = 100 # 样本数
theta = np.random.randn(4, 1) # 初始化参数
for iteration in range(n_iterations):
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta -= eta * gradients
# 打印得到的参数
print("得到的参数为:", theta)
# 绘制结果
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制原始数据点
ax.scatter(X1, X2, y, c='b', marker='o')
# 生成新数据点
X1_new = np.linspace(0, 2, 100)
X2_new = np.linspace(0, 3, 100)
X1_new, X2_new = np.meshgrid(X1_new, X2_new)
X3_new = (-theta[0] - theta[1] * X1_new - theta[2] * X2_new) / theta[3]
# 绘制平面
ax.plot_surface(X1_new, X2_new, X3_new, alpha=0.5)
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('y')
plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。