SGD代码实现python
时间: 2024-06-22 17:01:25 浏览: 5
SGD(Stochastic Gradient Descent,随机梯度下降)是一种常用的优化算法,用于训练机器学习模型。在Python中,我们可以使用深度学习库如TensorFlow或PyTorch来实现SGD。以下是一个简单的使用Python和TensorFlow实现SGD的示例:
```python
import tensorflow as tf
# 假设我们有一个简单的线性回归模型
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=1, input_shape=)
])
# 定义损失函数(如均方误差)和优化器(SGD)
loss_fn = tf.keras.losses.MeanSquaredError()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) # 学习率设为0.01
# 假设我们有一个数据集x_data和y_data
x_data = tf.constant([, , , ])
y_data = tf.constant([, , , ])
# 模型训练
@tf.function
def train_step(x, y):
with tf.GradientTape() as tape:
predictions = model(x)
loss = loss_fn(y, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
for epoch in range(100): # 进行100次迭代
for i in range(len(x_data)):
train_step(x_data[i:i+1], y_data[i:i+1])
```
在这个例子中,我们首先创建了一个简单的线性模型,然后定义了SGD优化器。在训练循环中,对于每个数据点,我们计算梯度并更新模型的权重。`tf.GradientTape`是TensorFlow用来跟踪计算以计算梯度的工具。