### 1、数据集
数据集使用的是Fashion mnist, 主要是衣服鞋子的图片。
### 2、代码讲解
**datasets:自动下载导入数据包的库**
**layers:调用全连接库**
**optimizers:参数更新步长,learning rate**
**Sequential: 串连接容器**
**metrics: 指标(Accuracy,Mean)**
```py
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 定义一个数据预处理函数
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x,y
# 下载fashion mnist 数据
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
print(x.shape, y.shape)
# 设置批量操作的数据大小,每个step处理的数据
batchsz = 128
# 把x, y,设置成可以批量抽取,shuffle:打乱数据
db = tf.data.Dataset.from_tensor_slices((x,y))
db = db.map(preprocess).shuffle(10000).batch(batchsz)
# 同理:x_test, y_test 设置成批量抽取
db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
db_test = db_test.map(preprocess).batch(batchsz)
# 创建一个迭代器,抽取数据
db_iter = iter(db)
# 抽取一个数据看一下格式
sample = next(db_iter)
print('batch:', sample[0].shape, sample[1].shape)
# 创建串联的全连接层模型,激活函数用relu,把维度由784变为10,因为图片只有10类
model = Sequential([
layers.Dense(256, activation=tf.nn.relu), # [b, 784] => [b, 256]
layers.Dense(128, activation=tf.nn.relu), # [b, 256] => [b, 128]
layers.Dense(64, activation=tf.nn.relu), # [b, 128] => [b, 64]
layers.Dense(32, activation=tf.nn.relu), # [b, 64] => [b, 32]
layers.Dense(10) # [b, 32] => [b, 10], 330 = 32*10 + 10
])
# 构建模型
model.build(input_shape=[None, 28*28])
# 查看模型的各种数据详情
model.summary()
# w = w - lr*grad,设置更新步长
optimizer = optimizers.Adam(lr=1e-3)
# 主运行方法
def main():
# 循环30次数据(一批数据重复训练)
for epoch in range(30):
# 批量抽取数据,每个step数据量为:128
for step, (x,y) in enumerate(db):
# x: [b, 28, 28] => [b, 784]
# y: [b]
x = tf.reshape(x, [-1, 28*28])
# 求导
with tf.GradientTape() as tape:
# [b, 784] => [b, 10]
logits = model(x)
y_onehot = tf.one_hot(y, depth=10)
# 计算loss mse(目前没使用这种loss)
loss_mse = tf.reduce_mean(tf.losses.MSE(y_onehot, logits))
# 计算 loss categorical_crossentropy
loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss_ce = tf.reduce_mean(loss_ce)
# 得到每个参数的导数方向
grads = tape.gradient(loss_ce, model.trainable_variables)
# 按照导数和更新步长,自动更新参数
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step % 100 == 0:
print(epoch, step, 'loss:', float(loss_ce), float(loss_mse))
# test,计算每个epoch的accury
total_correct = 0
total_num = 0
for x, y in db_test:
# x: [b, 28, 28] => [b, 784]
# y: [b]
x = tf.reshape(x, [-1, 28*28])
# [b, 10]
logits = model(x)
# logits => prob, [b, 10],求得概率
prob = tf.nn.softmax(logits, axis=1)
# [b, 10] => [b], int64,求得概率的最大下标
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
# correct: [b], True: equal, False: not equal
correct = tf.equal(pred, y)
# 计算1(True)的个数
correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))
# 批量的求和要汇总
total_correct += int(correct)
total_num += x.shape[0]
# 计算每个epoch的accury
acc = total_correct / total_num
print(epoch, 'test acc:', acc)
if __name__ == '__main__':
main()
```

Tensorflow: 图片分类实战