keras.datasets.fashion_mnist 其中数据涵盖了10个类别,单间服装的分辨率(28x28像素) 步骤和部分代码分析: 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(*)
时间: 2024-02-05 21:13:38 浏览: 83
1. 读取数据:
```python
import tensorflow as tf
from tensorflow import keras
# 读取数据
(train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()
```
2. 进行模型编写:
```python
num_classes = 10
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)), # 将28x28的像素矩阵展开为一维向量
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(num_classes, activation=tf.nn.softmax)
])
```
3. 选择SGD优化器:
```python
sgd = keras.optimizers.SGD(lr=0.01)
model.compile(optimizer=sgd,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
4. 训练和评估:
```python
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
```
5. 打印模型结构:
```python
model.summary()
```
6. 保存模型:
```python
# 保存成ckpt格式
checkpoint_path = "model_checkpoint.ckpt"
checkpoint = ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1)
model.fit(train_images, train_labels, epochs=10, callbacks=[checkpoint])
# 保存成h5格式
model.save_weights('model.h5')
```
阅读全文