如何使用TensorFlow在Python中对Fashion MNIST数据集进行预测?
TensorFlow是谷歌提供的机器学习框架。它是一个开源框架,与Python一起用于实现算法、深度学习应用等等。它被用于研究和生产目的。它具有优化技术,可以快速执行复杂的数学运算。这是因为它使用NumPy和多维数组。这些多维数组也被称为“张量”。
可以使用以下代码在Windows上安装’tensorflow’软件包 −
pip install tensorflow
张量是TensorFlow中使用的一种数据结构。它有助于连接流程图中的边缘。这个流程图被称为“数据流图”。张量不过是多维数组或列表。
“Fashion MNIST”数据集包含不同种类的服装图片。它包含超过7万张属于10个不同类别的衣服的灰度图像。这些图像的分辨率很低(28 x 28个像素)。
我们使用Google Colab来运行以下代码。Google Colab或Colaboratory可以在浏览器上运行Python代码,无需任何配置,并且可以免费访问GPU(图形处理单元)。Colaboratory是基于Jupyter Notebook构建的。
以下是用于进行预测的代码片段 −
更多Python相关文章,请阅读:Python 教程
示例
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print("The predictions are being made ")
print(predictions[0])
np.argmax(predictions[0])
print("The test labels are")
print(test_labels[0])
def plot_image(i, predictions_array, true_label, img):
true_label, img = true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]), color=color)
def plot_value_array(i, predictions_array, true_label):
true_label = true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('green')
代码来源 − https://www.tensorflow.org/tutorials/keras/classification
输出
The predictions are being made
[1.3008227e−07 9.4930819e−10 2.0181861e−09 5.4944155e−10 3.8257373e−11
1.3896286e−04 1.4776078e−08 3.1724274e−03 9.4210514e−11 9.9668854e−01]
The test labels are
9
解释
-
一旦模型已被训练,就需要进行测试。
-
可以利用已建成的模型对图像进行预测。
-
线性输出、对数和一个softmax层都与之相关联。
-
softmax层有助于将对数转换为概率。
-
这样做可以更容易地解释所作的预测。
-
定义了“plot_value_array”方法,它显示实际值和预测值。
极客教程