如何使用 Python 和 TensorFlow 来可视化训练结果?


可以使用 Python 和 TensorFlow 结合 ‘matplotlib’ 库来可视化训练结果。 ‘plot’ 方法用于在控制台上绘制数据。

阅读更多: 什么是 TensorFlow 以及 Keras 如何与 TensorFlow 协作创建神经网络?

我们将使用 Keras Sequential API,它有助于构建一个顺序模型,用于处理简单的层堆栈,其中每一层只有一个输入张量和一个输出张量。

包含至少一层卷积层的神经网络被称为卷积神经网络。我们可以 使用卷积神经网络来构建学习模型。 

使用 keras.Sequential 模型创建一个图像分类器,并使用 preprocessing.image_dataset_from_directory 加载数据。数据可以高效地从磁盘加载。可以识别过拟合并应用技术来减轻它。这些技术包括数据增强和 dropout。有 3700 张花卉图像。此数据集包含 5 个子目录,每个子目录对应一个类别。它们是:雏菊、蒲公英、玫瑰、向日葵和郁金香。

我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助在浏览器上运行 Python 代码,无需任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 是基于 Jupyter Notebook 构建的。

示例

print("Calculating the accuracy")
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
print("Calculating the loss")
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(epochs)
print("The results are being visualized")
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)

plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

代码来源 −https://tensorflowcn.cn/tutorials/images/classification

输出

Calculating the accuracy
Calculating the loss
The results are being visualized

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 以上图表表明训练精度和验证精度并不一致。

  • 该模型在验证数据集上仅达到了大约 60% 的精度。

  • 这被称为过拟合。

  • 训练精度随时间线性增加,但验证精度在训练过程中停滞在 60% 左右。

  • 当训练样本数量较少时,模型会从训练样本中的噪声或不需要的细节中学习。

  • 这会对模型在新样本上的性能产生负面影响。

  • 由于过拟合,模型将无法在新数据集上很好地泛化。

  • 有很多方法可以避免过拟合。我们将使用数据增强来克服过拟合。

更新于: 2021年2月22日

802 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告