tensorflow2.0 学习代码之fashion_mnist

本文详细介绍了如何使用TensorFlow2.0进行fashion_mnist数据集的训练,包括安装TensorFlow,配置Jupyter Notebook的代码补全功能,数据预处理,构建多层神经网络模型,模型编译,训练过程及结果可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要用tensorflow2.0 跑一下fashion_mnist的测试代码

安装tensorflow2.0 后

在anaconda promt安装pip install numpy pandas matplotlib sklearn
上面速度慢,用 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas matplotlib sklearn

Jupyter Notebook添加代码自动补全功能

pip install jupyter_contrib_nbextensions
配置:安装完之后需要配置 nbextension,注意配置的时候要确保已关闭 Jupyter Notebook
jupyter contrib nbextension install --user --skip-running-check
启动 Jupyter Notebook,勾选设置
上面两个步骤都没报错后,启动 Jupyter Notebook,上面选项栏会出现 Nbextensions 的选项
点开 Nbextensions 的选项,并勾选 Table of Contents 和Hinterland
自动补全功能
按 Tab 键即可使用

输入 jupyter notebook 从命令行直接跳到jupyter notebook界面
import tensorflow as tf
import pandas as pd
(train_image,train_label),(test_image,test_lebel) = tf.keras.datasets.fashion_mnist.load_data()

上面的代码下载太慢,网上直接下载放到自己的文件夹内:C盘用户文件夹的.keras文件下的datasets目录里(不要解压哦)参考https://blog.youkuaiyun.com/weixin_44604887/article/details/105099177

fashion_mnist = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images.shape
将标签(0到9的 int)进行onehot编码
train_label_onehot = tf.keras.utils.to_categorical(train_labels)
test_label_onehot = tf.keras.utils.to_categorical(test_labels)

构建模型
model =tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation=‘relu’))
model.add(tf.keras.layers.Dense(128,activation=‘relu’))
model.add(tf.keras.layers.Dense(128,activation=‘relu’))
model.add(tf.keras.layers.Dense(10,activation = ‘softmax’))

编译模型
model.compile(optimizer =‘adam’,loss=‘categorical_crossentropy’,metrics=[‘acc’])

可以查看模型有多少参数
model.summary()

训练
history = model.fit(train_images,train_label_onehot,epochs = 10,
validation_data=(test_images,test_label_onehot))

把训练中的记录 history画出来
history.history.keys()的运行结果为dict_keys([‘loss’, ‘acc’, ‘val_loss’, ‘val_acc’])

分别画测试集和验证集的损失和准确率
plt.plot(history.epoch,history.history.get(‘loss’),label = ‘loss’)
plt.plot(history.epoch,history.history.get(‘val_loss’),label = ‘val_loss’)
plt.legend()

plt.plot(history.epoch,history.history.get(‘acc’),label = ‘acc’)
plt.plot(history.epoch,history.history.get(‘val_acc’),label = ‘val_acc’)
plt.legend()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值