多元线性回归梯度下降法 python代码
时间: 2023-04-08 20:00:45 浏览: 104
以下是多元线性回归梯度下降法的 Python 代码:
```python
import numpy as np
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
for i in range(num_iters):
h = X.dot(theta)
loss = h - y
gradient = X.T.dot(loss) / m
theta = theta - alpha * gradient
return theta
X = np.array([[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6]])
y = np.array([[1], [2], [3], [4]])
theta = np.array([[0], [0], [0]])
alpha = 0.01
num_iters = 1000
theta = gradient_descent(X, y, theta, alpha, num_iters)
print(theta)
```
希望对你有帮助!
相关问题
多元线性回归梯度下降法 python
可以回答这个问题。多元线性回归梯度下降法是一种常用的机器学习算法,可以用于预测多个自变量对一个因变量的影响。在 Python 中,可以使用 NumPy 和 Pandas 库来实现多元线性回归梯度下降法。
numpy多元线性回归梯度下降
在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。