本文不做多余解释,主要是衔接上一章TensorFlow-2.x-03-从0开始的多分类逻辑回归内容,使用TF-2.x来快速实现多分类逻辑回归。
1、获取/读取数据集,归一化数据
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
print(x_train.shape,y_train.shape)
2、定义及初始化模型
def net():
net=tf.keras.Sequential()
net.add(tf.keras.layers.Flatten(input_shape=(28,28)))
net.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) #输出10个神经元,softmax用于分类
return net
3、定义优化器
optimizer = tf.keras.optimizers.SGD(0.1)
4、模型训练
model.compile(optimizer=optimizer,
loss = 'sparse_categorical_crossentropy', #交叉熵损失
metrics=['accuracy']) # 准确率
model.fit(x_train,y_train,epochs=5,batch_size=256)
训练结果:
#5、模型验证
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test Acc:',test_acc)
验证结果:
附上所有源码:
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import data as tfdata
from tensorflow.keras.datasets import fashion_mnist
# 1、获取和读取数据
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
print(x_train.shape,y_train.shape)
#2、定义及初始化模型
def net():
net=tf.keras.Sequential()
net.add(tf.keras.layers.Flatten(input_shape=(28,28)))
net.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) #输出10个神经元,softmax用于分类
return net
model=net()
model.summary()
#3、定义优化器
optimizer = tf.keras.optimizers.SGD(0.1)
# 4、模型训练
model.compile(optimizer=optimizer,
loss = 'sparse_categorical_crossentropy', #交叉熵损失
metrics=['accuracy']) # 准确率
model.fit(x_train,y_train,epochs=5,batch_size=256)
# 5、模型验证
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test Acc:',test_acc)