梯度下降法代码 python
时间: 2023-11-03 17:57:27 浏览: 104
python实现梯度下降算法的实例详解
梯度下降法是一种常用的优化算法,用于求解函数的最小值。下面是一个简单的梯度下降法的 Python 代码示例:
```python
import numpy as np
def gradient_descent(x, y, learning_rate, num_iterations):
num_samples = len(y)
num_features = len(x[0])
theta = np.zeros(num_features) # 初始化参数
for _ in range(num_iterations):
gradient = np.zeros(num_features) # 初始化梯度
for i in range(num_samples):
h = np.dot(theta, x[i]) # 计算预测值
loss = h - y[i]
gradient += loss * x[i] # 计算梯度
theta -= (learning_rate / num_samples) * gradient # 更新参数
return theta
# 示例数据
x = np.array([[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6], [1, 6, 7]])
y = np.array([3, 4, 5, 6, 7])
# 超参数设置
learning_rate = 0.01
num_iterations = 1000
# 调用梯度下降算法
theta = gradient_descent(x, y, learning_rate, num_iterations)
print("参数 theta:", theta)
```
阅读全文