生成批量梯度下降python代码
时间: 2023-05-16 17:06:43 浏览: 72
以下是一个简单的批量梯度下降的 Python 代码示例:
```
import numpy as np
# 定义数据集
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 1, 1, 0])
# 定义模型参数
theta = np.zeros(X.shape[1])
# 定义学习率和迭代次数
alpha = 0.01
num_iters = 1000
# 批量梯度下降
for i in range(num_iters):
h = 1 / (1 + np.exp(-np.dot(X, theta)))
gradient = np.dot(X.T, (h - y)) / y.size
theta -= alpha * gradient
# 输出最终的模型参数
print(theta)
```
这段代码实现了一个简单的逻辑回归模型,使用批量梯度下降算法来优化模型参数。其中,X 是输入数据集,y 是对应的标签,theta 是模型参数,alpha 是学习率,num_iters 是迭代次数。在每一次迭代中,我们计算模型的预测值 h,然后计算梯度 gradient,并更新模型参数 theta。最终,我们输出最终的模型参数。
相关问题
小批量梯度下降法代码
以下是一个使用小批量梯度下降法的线性回归代码示例:
```python
import numpy as np
# 定义小批量梯度下降函数
def mini_batch_gradient_descent(X, y, theta, learning_rate=0.01, batch_size=20, num_iterations=1000):
m = len(y)
for i in range(num_iterations):
# 随机选择一批样本
batch_indices = np.random.randint(0, m, batch_size)
X_batch = X[batch_indices]
y_batch = y[batch_indices]
# 计算梯度
hypothesis = np.dot(X_batch, theta)
loss = hypothesis - y_batch
gradient = np.dot(X_batch.T, loss) / batch_size
# 更新参数
theta = theta - learning_rate * gradient
return theta
# 生成随机数据
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# 添加偏置项
X_b = np.c_[np.ones((100, 1)), X]
# 初始化参数
theta = np.random.randn(2, 1)
# 使用小批量梯度下降法训练模型
theta = mini_batch_gradient_descent(X_b, y, theta)
# 输出训练得到的参数
print(theta)
```
该代码使用了随机选择一批样本的方法来计算梯度,从而实现小批量梯度下降法。其中,`X`和`y`分别是输入特征和标签,`theta`是模型参数,`learning_rate`是学习率,`batch_size`是每批样本的数量,`num_iterations`是迭代次数。函数返回训练得到的参数`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()
```
这段代码会生成一个损失函数随迭代次数变化的图像,可以清晰地看到损失函数在不断下降,说明梯度下降在有效地优化参数。