Python 如何使用Python利用Tensorflow和预训练模型进行数据评估和预测?

Python 如何使用Python利用Tensorflow和预训练模型进行数据评估和预测?

使用“evaluate”和“predict”方法可以利用Tensorflow和预训练模型进行数据评估和预测。首先对输入的一批图像进行平坦化处理。然后对模型应用sigmoid函数,以便返回logit值。

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

我们将通过从预训练网络进行转移学习来理解如何对猫和狗的图像进行分类。图像分类的转移学习背后的直觉是,如果一个模型在一个大型和通用的数据集上进行训练,那么这个模型可以被用来有效地作为视觉世界的通用模型。它已经学会了特征映射,这意味着用户不需要从头开始在大型数据集上训练一个大型模型。

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

阅读更多:Python 教程

示例

print("Evaluation and prediction")
loss, accuracy = model.evaluate(test_dataset)
print('Test accuracy is :', accuracy)
print("The batch of image from test set is retrieved")
image_batch, label_batch = test_dataset.as_numpy_iterator().next()
predictions = model.predict_on_batch(image_batch).flatten()
print("The sigmoid function is applied on the model, it returns logits")
predictions = tf.nn.sigmoid(predictions)
predictions = tf.where(predictions < 0.5, 0, 1)
print('Predictions are:\n', predictions.numpy())
print('Labels are:\n', label_batch)

代码来源 https://www.tensorflow.org/tutorials/images/transfer_learning

输出

Evaluation and prediction
6/6 [==============================] - 3s 516ms/step - loss: 0.0276 - accuracy: 0.9844
Test accuracy is : 0.984375
The batch of image from test set is retrieved
The sigmoid function is applied on the model, it returns logits
Predictions are:
[1 1 1 1 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 1 1 0 1 0 0 1 1 1 0 1 0 1]
Labels are:
[1 1 1 1 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 1 1 0 1 0 0 1 1 1 0 1 0 1]

解释

  • 现在模型可以用于预测和评估数据。
  • 当图像作为输入时,进行预测。
  • 预测必须是图像是狗还是猫。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程