梯度下降法python代码
时间: 2023-10-13 21:26:13 浏览: 92
梯度下降法是一种常见的优化算法,主要用于最小化损失函数。下面是一份使用Python实现的梯度下降法代码示例:
```python
import numpy as np
def gradient_descent(X, y, theta, alpha, iterations):
"""
X: 特征矩阵
y: 标签向量
theta: 参数向量
alpha: 学习率
iterations: 迭代次数
"""
m = len(y)
for i in range(iterations):
h = X.dot(theta)
loss = h - y
gradient = X.T.dot(loss) / m
theta = theta - alpha * gradient
return theta
```
其中,X是一个m * n的特征矩阵,y是一个m * 1的标签向量,theta是一个n * 1的参数向量,alpha是学习率,iterations是迭代次数。函数的过程是每次计算损失函数的梯度,然后根据学习率和梯度更新参数向量。最后返回更新后的参数向量。
相关问题
梯度下降算法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)
```
希望对你有帮助!
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)