python梯度下降算法代码演示
时间: 2024-10-14 15:00:35 浏览: 41
gradient_descent_机器学习_toodj1_python_descent_梯度下降法_
Python中梯度下降算法通常用于优化机器学习模型中的参数,通过迭代更新的方式沿着成本函数下降最快的方向调整参数值。这里是一个简单的线性回归梯度下降示例:
```python
import numpy as np
def gradient_descent(x, y, learning_rate=0.01, num_iterations=1000):
# 初始化权重
m = b = 0
n = len(x)
for _ in range(num_iterations):
# 梯度计算
y_pred = m * x + b
dm = -(2/n) * sum(x * (y - y_pred))
db = -(2/n) * sum(y - y_pred)
# 更新权重
m -= learning_rate * dm
b -= learning_rate * db
return m, b
# 示例数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
m, b = gradient_descent(x, y)
print(f"斜率 (m): {m}, 截距 (b): {b}")
阅读全文