编写在训练的时候画loss损失图的代码
时间: 2024-11-22 07:35:52 浏览: 5
编写训练过程中绘制损失曲线(Loss Curve)的代码通常是在深度学习训练框架中,比如TensorFlow或PyTorch。这里是一个简单的例子,我们将展示如何在Python的TensorFlow环境中做这件事:
```python
import tensorflow as tf
import matplotlib.pyplot as plt
# 定义一个简单模型并编译它
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(input_dim,))
])
model.compile(optimizer='adam', loss='mean_squared_error')
# 创建一个Callback来记录历史损失
class LossHistory(tf.keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.losses = []
def on_batch_end(self, batch, logs={}):
self.losses.append(logs.get('loss'))
history = LossHistory()
# 开始训练
EPOCHS = 50
history_dict = model.fit(x_train, y_train,
epochs=EPOCHS,
validation_data=(x_test, y_test),
callbacks=[history])
# 绘制损失曲线
plt.figure()
plt.plot(history.history['loss'], label='Training Loss')
if 'val_loss' in history.history:
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Loss vs Epochs')
plt.legend()
plt.show()
阅读全文