import numpy as np
import warnings
warnings.filterwarnings('ignore')
# 构造数据
X = 2 * np.random.rand(100, 1)
y = 1 + 5 * X + np.random.rand(100, 1)
# 加入X0
X_b = np.c_[np.ones((100, 1)), X]
eta = 0.1
n_iterations = 1000
m = 100
theta = np.random.randn(2, 1)
for iterations in range(n_iterations):
gradients = 2 / m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - eta * gradients
print(theta)
运行结果: