如何使用Tensorflow对增强数据的新数据进行预测?


训练完成后,可以将构建的模型用于增强的新数据。这可以通过“预测”方法来实现。需要验证的数据首先加载到环境中。然后,通过将其从图像转换为数组来对其进行预处理。接下来,在此数组上调用预测方法。

阅读更多: 什么是 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 之上。

当训练样本数量较少时,模型会从训练样本中的噪声或不需要的细节中学习。这会对模型在新样本上的性能产生负面影响。

由于过拟合,模型将无法在新数据集上很好地泛化。有许多方法可以避免过拟合。我们可以使用 dropout 技术来克服过拟合。可以通过在网络中引入 dropout 来减少过拟合。这被认为是一种正则化形式。这有助于使模型接触到更多的数据方面,从而帮助模型更好地泛化。

当将 dropout 应用于某一层时,它会在训练过程中随机丢弃该层中的若干输出单元。这是通过将激活函数设置为 0 来完成的。Dropout 技术将分数作为输入值(如 0.1、0.2、0.4 等)。这个数字 0.1 或 0.2 基本上表示应用层中 10% 或 20% 的输出单元是随机的。

数据增强通过使用随机变换增强现有示例来生成额外的训练数据,这些随机变换将产生看起来可信的图像。以下是一个示例

示例

print("The model built is being used to predict new data")
sunflower_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/592px-Red_sunflower.jpg"
sunflower_path = tf.keras.utils.get_file('Red_sunflower', origin=sunflower_url)
img = keras.preprocessing.image.load_img(
   sunflower_path, target_size=(img_height, img_width)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
   "This image likely belongs to {} with {:.2f} percent confidence."
   .format(class_names[np.argmax(score)], 100 * np.max(score))
)

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

输出

The model built is being used to predict new data
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/592px-Red_sunflower.jpg
122880/117948 [===============================] - 0s 0us/step
A batch is created
This image likely belongs to sunflowers with 99.07 percent confidence.

解释

  • 先前构建的模型用于从未见过的新的数据。
  • 使用“预测”方法预测数据集的相关值。
  • 做出预测后,计算置信度水平。
  • 这将显示在控制台上。

更新于: 2021年2月22日

356 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.