import numpy as np import matplotlib.pyplot as plt
生成随机数据
np.random.seed(0) X = 2 * np.random.rand(100, 1) y = 3 + 4 * X + np.random.randn(100, 1)
初始化模型参数
theta = np.random.randn(2, 1)
添加偏置项
X_b = np.c_[np.ones((100, 1)), X]
定义训练迭代次数和学习率
num_iterations = 1000 learning_rate = 0.1
训练模型
for iteration in range(num_iterations): gradients = 2 * X_b.T.dot(X_b.dot(theta) - y) / len(y) theta -= learning_rate * gradients
绘制数据和拟合直线
plt.scatter(X, y) plt.plot(X, X_b.dot(theta), color='red') plt.xlabel('X') plt.ylabel('y') plt.show()