机器学习TensorFlow---Fashion MNIST基本图像分类
实验介绍:
利用数据集Fashion MNIST中的数据信息,进行机器学习,构建模型,训练模型。完成对该数据集中的数据分类(对运动鞋和衬衫等服装图像进行分类)。本实验主要使用 tf.keras,它是 TensorFlow 中用来构建和训练模型的高级 API。
导入 Fashion MNIST 数据:
头文件展示:
1 2 3 | import tensorflow as tf import numpy as np import matplotlib.pyplot as plt |
直接从 TensorFlow 中访问 Fashion MNIST。直接从 TensorFlow 中导入和加载 Fashion MNIST 数据,本数据集中包含了6000张训练数据和1000张测试数据:
1 2 | fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() |
为每一个标签(labels)命名:
1 2 3 | #标签0-9分别对应的衣服 class_names = [ 'T-shirt/top' , 'Trouser' , 'Pullover' , 'Dress' , 'Coat' , 'Sandal' , 'Shirt' , 'Sneaker' , 'Bag' , 'Ankle boot' ] |
标签命名前,标签命名后:
数据预处理一下,将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,请将这些值除以 255。请务必以相同的方式对训练集和测试集进行预处理:
1 2 | train_images = train_images / 255 test_images = test_images / 255 |
数据浏览,展示前25条数据:
1 2 3 4 5 6 7 8 9 | plt.figure(figsize = ( 10 , 10 )) for i in range ( 25 ): plt.subplot( 5 , 5 , i + 1 ) plt.xticks([]) plt.yticks([]) # plt.cm.binary的作用是图片将以黑白色显示 plt.imshow(train_images[i], cmap = plt.cm.binary) plt.xlabel(class_names[train_labels[i]]) plt.show() |
构建模型:
设置层:
1 2 3 4 5 | model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape = ( 28 , 28 )), tf.keras.layers.Dense( 128 , activation = 'relu' ), tf.keras.layers.Dense( 10 ) ]) |
编译模型:
1 2 3 | model. compile (optimizer = 'adam' , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = True ), metrics = [ 'accuracy' ]) |
训练模型:
训练神经网络模型需要执行以下步骤:
- 将训练数据馈送给模型。在本例中,训练数据位于
train_images
和train_labels
数组中。 - 模型学习将图像和标签关联起来。
- 要求模型对测试集(在本例中为
test_images
数组)进行预测。 - 验证预测是否与
test_labels
数组中的标签相匹配。
训练模型:
1 | model.fit(train_images, train_labels, epochs = 10 ) |
模型测试:
1 2 | test_loss, test_acc = model.evaluate(test_images, test_labels, verbose = 2 ) print ( "测试准确率为: " ,test_acc) |
模型预测:
先建立预测模型:
1 2 | probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()]) |
预测一下:
1 | predictions = probability_model.predict(train_images) |
看看预测的第一个数据怎么样:
1 | predictions[ 0 ] |
1 2 | [ 2.1990630e - 14 9.6575387e - 11 8.7644484e - 20 1.4134983e - 15 3.9952511e - 13 2.2158854e - 05 7.6434464e - 14 8.5105496e - 03 3.5996098e - 14 9.9146724e - 01 ] |
可以发现,对于这个数据,是该模型预测出的该数据所属标签概率。
具体查看该数据最有可能的那个标签:
1 | print (np.argmax(predictions[ 0 ])) |
1 | 9 |
实验结束。
__EOF__

本文作者:从荣
本文链接:https://www.cnblogs.com/rongrongrong/p/17528987.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/rongrongrong/p/17528987.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!