You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Keras中训练准确率起始Epoch为0、绘图Epoch轴从1开始显示的问题

Solution to Fix Epoch Indexing in Keras Training History and Plots

Let's work through resolving both of your issues clearly:

Why This Happens

Keras uses 0-based indexing for storing training history entries. When you train for 20 epochs, the hist.history lists (like accuracy and val_accuracy) will have 20 elements indexed from 0 to 19—these correspond directly to the 1st through 20th training epochs. This is why your plot shows an x-range of 0-19 instead of the intuitive 1-20.

Step-by-Step Fix

1. Adjust the Plot to Use 1-Based Epoch Numbers

Instead of relying on matplotlib's default 0-based x-values, explicitly create a list of epoch numbers starting at 1. Here's your modified code:

hist = model.fit(train_generator, validation_data=val_generator, epochs=20, batch_size=batchsize)

plt.figure(figsize=(8,8))
plt.subplot(2,1,1)

# Generate 1-based epoch sequence (1 to 20)
epochs = range(1, len(hist.history['accuracy']) + 1)

# Plot using the 1-based epoch values as the x-axis
plt.plot(epochs, hist.history['accuracy'], marker='o')
plt.plot(epochs, hist.history['val_accuracy'], marker='p')

plt.axis(ymin=0.0, ymax=1)
plt.grid()
plt.title('VGG16 Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
# Optional: Force x-ticks to show every epoch number for clarity
plt.xticks(epochs)
plt.legend(['Training Accuracy', 'Validation Accuracy'])
plt.show()

2. Display 1-Based Epochs in Accuracy Records (If Needed)

If you want to print or log accuracy values with 1-based epoch labels (instead of 0-based), loop through the history with an offset:

for epoch_num, acc, val_acc in zip(epochs, hist.history['accuracy'], hist.history['val_accuracy']):
    print(f"Epoch {epoch_num}: Training Accuracy = {acc:.4f}, Validation Accuracy = {val_acc:.4f}")

Key Changes Explained

  • epochs = range(1, len(hist.history['accuracy']) + 1): Creates a sequence from 1 to your total number of epochs (20), aligning with how we naturally count training cycles.
  • Plotting with epochs as the x-axis: Replaces the default 0-based indices with human-readable 1-based epoch numbers, fixing your plot's x-range issue.
  • plt.xticks(epochs): Optional but ensures every epoch number is visible on the x-axis, making the plot easier to interpret.

This solution will resolve both problems: your plot will now show an x-range of 1 to 20, and any printed accuracy records can be labeled with intuitive 1-based epoch numbers.

内容的提问来源于stack exchange,提问作者Monika Roopak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:37:37