使用TensorFlow实现时装分类,数据来源: keras.datasets.fashion_mnist,步骤和部分代码分析: 1.读取数据 2.进行模型编写: 双层:128神经元, 全链接层10个类别输出 Dense(128, activation=tf.nn.relu) 3.选择SGD优化器 4.训练和评估 5.打印模型结构 6.保存模型(model.save_weights): a)保存成ckpt b)保存成h5文件 keras.callbacks import ModelCheckpoint(*),使用pycharm语言进行代码书写
时间: 2024-02-05 22:10:34 浏览: 188
以下是使用TensorFlow实现时装分类的代码和注释:
``` python
import tensorflow as tf
from tensorflow import keras
from keras.callbacks import ModelCheckpoint
# 1. 读取数据
(train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()
# 2. 模型编写
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)), # 展平层,将输入的28x28的图像展平为一维向量
keras.layers.Dense(128, activation=tf.nn.relu), # 第一层全连接层,128个神经元,激活函数为ReLU
keras.layers.Dense(128, activation=tf.nn.relu), # 第二层全连接层,128个神经元,激活函数为ReLU
keras.layers.Dense(10, activation=tf.nn.softmax) # 输出层,输出10个类别的概率分布
])
# 3. 选择SGD优化器
sgd = keras.optimizers.SGD(lr=0.01)
# 4. 训练和评估
model.compile(optimizer=sgd,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 设置模型保存路径和文件名
checkpoint_path = "model/checkpoint.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
# 定义回调函数,每5个epoch保存一次模型
cp_callback = ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1, period=5)
# 开始训练模型
model.fit(train_images, train_labels, epochs=50, validation_data=(test_images, test_labels), callbacks=[cp_callback])
# 5. 打印模型结构
model.summary()
# 6. 保存模型
# 6.a. 保存成ckpt格式
model.save_weights(checkpoint_path.format(epoch=0))
# 6.b. 保存成h5格式
model.save('model/fashion_mnist.h5')
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)