numpy多元线性回归梯度下降
时间: 2024-01-18 20:03:41 浏览: 30
在NumPy中,可以使用梯度下降法来求解多元线性回归问题。下面是一个演示多元线性回归梯度下降的例子:
```python
import numpy as np
# 定义输入特征矩阵X和目标变量向量y
X = np.array([[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6]])
y = np.array([5, 6, 7, 8])
# 初始化参数向量theta
theta = np.zeros(X.shape[1])
# 定义梯度下降的学习率和迭代次数
learning_rate = 0.01
iterations = 1000
# 使用梯度下降法更新参数向量theta
for i in range(iterations):
# 计算预测值
y_pred = np.dot(X, theta)
# 计算误差
error = y_pred - y
# 计算梯度
gradient = np.dot(X.T, error) / len(y)
# 更新参数向量theta
theta -= learning_rate * gradient
# 打印最终的参数向量theta
print("Parameters: ", theta)
```
在上述代码中,我们首先定义了输入特征矩阵X和目标变量向量y。然后,我们初始化参数向量theta为全零向量。接下来,我们使用梯度下降法来更新参数向量theta,通过迭代计算预测值、误差和梯度,并更新参数向量theta。最后,我们打印出最终的参数向量theta。