用Python实现批量梯度下降
时间: 2023-11-05 12:25:08 浏览: 44
批量梯度下降算法是机器学习中的一种优化方法,可以用于训练一些模型,如线性回归、神经网络等。在Python中,可以使用NumPy库来实现批量梯度下降算法。以下是一段示例代码:
import numpy as np
def batch_gradient_descent(X, y, alpha=0.01, epochs=100):
n, m = X.shape
theta = np.zeros((m, 1))
for i in range(epochs):
h = np.dot(X, theta)
loss = h - y
gradient = np.dot(X.T, loss) / n
theta = theta - alpha * gradient
return theta
其中,X和y分别代表特征矩阵和目标向量,alpha和epochs分别代表学习率和迭代次数。该函数返回的是最优的参数向量theta。
相关问题
Python matplotlib实现批量梯度下降
的过程中,如何画出损失函数随迭代次数变化的图像?
你可以使用以下代码来画出损失函数随迭代次数变化的图像:
```python
import matplotlib.pyplot as plt
# 初始化参数
theta = np.zeros([2, 1])
theta[0] = -10
theta[1] = -1
# 迭代次数和步长
iterations = 100
alpha = 0.01
# 初始化数据
X = np.random.rand(100)
Y = np.random.rand(100)
# 定义损失函数
def compute_cost(theta, X, Y):
m = len(Y)
predictions = X.dot(theta)
cost = 1/(2*m) * np.sum(np.square(predictions-Y))
return cost
# 执行梯度下降
def gradient_descent(theta, X, Y, alpha, iterations):
m = len(Y)
cost_history = np.zeros(iterations)
theta_history = np.zeros([iterations, 2])
for i in range(iterations):
predictions = X.dot(theta)
theta = theta - alpha * (1/m) * X.T.dot(predictions-Y)
theta_history[i] = theta.T
cost_history[i] = compute_cost(theta, X, Y)
return theta_history, cost_history
# 运行梯度下降并记录每次的theta和cost
theta_history, cost_history = gradient_descent(theta, X, Y, alpha, iterations)
# 画出损失函数随迭代次数变化的图像
plt.plot(range(iterations), cost_history)
plt.xlabel('迭代次数')
plt.ylabel('损失函数')
plt.show()
```
这段代码会生成一个损失函数随迭代次数变化的图像,可以清晰地看到损失函数在不断下降,说明梯度下降在有效地优化参数。
python实现小批量梯度下降算法
小批量梯度下降算法是梯度下降算法的一种改进,它不是在整个数据集上计算梯度,而是在每次迭代中随机选择一小部分数据进行计算。这样可以加快训练速度,同时也可以使模型更加稳定。
以下是Python实现小批量梯度下降算法的代码:
```python
import numpy as np
# 定义损失函数
def loss_function(X, y, w):
m = len(X)
y_pred = np.dot(X, w)
loss = np.sum((y_pred - y) ** 2) / (2 * m)
return loss
# 定义小批量梯度下降算法
def mini_batch_GD(X, y, w, learning_rate, num_iterations, batch_size):
m = len(X)
num_batches = m // batch_size
for i in range(num_iterations):
# 随机打乱数据集
permutation = np.random.permutation(m)
X_shuffled = X[permutation]
y_shuffled = y[permutation]
for j in range(num_batches):
# 选择一个小批量数据
start_index = j * batch_size
end_index = (j + 1) * batch_size
X_batch = X_shuffled[start_index:end_index]
y_batch = y_shuffled[start_index:end_index]
# 计算梯度并更新参数
y_pred = np.dot(X_batch, w)
gradient = np.dot(X_batch.T, (y_pred - y_batch)) / batch_size
w -= learning_rate * gradient
# 计算损失并输出
loss = loss_function(X, y, w)
print('iteration %d: loss=%f' % (i+1, loss))
return w
```
其中,X是数据集特征矩阵,y是标签向量,w是模型参数向量,learning_rate是学习率,num_iterations是迭代次数,batch_size是每个小批量数据的大小。在每次迭代中,我们首先将数据集随机打乱,然后选择一个小批量数据进行计算,计算梯度并更新参数。最后计算损失并输出。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)