梯度下降法python代码
时间: 2023-05-20 07:06:26 浏览: 69
以下是一个简单的梯度下降法的 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 = np.dot(X, theta)
loss = h - y
gradient = np.dot(X.T, loss) / m
theta = theta - alpha * gradient
return theta
```
其中,X 是输入特征矩阵,y 是输出向量,theta 是参数向量,alpha 是学习率,num_iters 是迭代次数。函数的作用是通过梯度下降法来优化参数 theta,使得模型的预测结果与真实值之间的误差最小化。
相关问题
梯度下降算法python代码
梯度下降算法是一种常用的优化算法,用于求解函数的最小值。以下是一个简单的梯度下降算法的Python代码示例:
```python
import numpy as np
def gradient_descent(X, y, learning_rate, num_iterations):
num_samples, num_features = X.shape
theta = np.zeros(num_features) # 初始化参数向量
for i in range(num_iterations):
# 计算预测值
y_pred = np.dot(X, theta)
# 计算误差
error = y_pred - y
# 计算梯度
gradient = np.dot(X.T, error) / num_samples
# 更新参数
theta -= learning_rate * gradient
return theta
# 示例数据
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y = np.array([4, 7, 10])
# 调用梯度下降算法
learning_rate = 0.01
num_iterations = 1000
theta = gradient_descent(X, y, learning_rate, num_iterations)
print("最优参数:", theta)
```
相关问题:
1. 什么是梯度下降算法?
2. 如何选择学习率和迭代次数?
3. 梯度下降算法的优缺点是什么?
4. 还有哪些常用的优化算法?
多元线性回归梯度下降法 python代码
以下是多元线性回归梯度下降法的 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)
```
希望对你有帮助!