三种思路构建fashion_mnist图像识别模型
数据是对衣服、裤子、鞋子等图片的十分类
模型很简单,主要让大家区分三种建模思路的区别,直接上代码:
import tensorflow as tf
fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train),(x_test, y_test) = fashion.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# 顺序模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
#函数模型
inputs = tf.keras.Input(shape=(28,28))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(128,activation='relu')(x)
predictions = tf.keras.layers.Dense(10,activation='softmax')(x)
model = tf.keras.Model(inputs,predictions)
#子类化模型
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel,self).__init__()
self.D1 = tf.keras.layers.Flatten()
self.D2 = tf.keras.layers.Dense(128,activation='relu')
self.D3 = tf.keras.layers.Dense(10,activation='softmax')
def call(self,inputs):
x = self.D1(inputs)
x = self.D2(x)
x = self.D3(x)
return x
model = MyModel()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()
三种模型的网络结构上是一样的,输出结果如下:
识别准确度有待提高,毕竟模型很简单嘛,大家可以把dense层换成CNN,提升很高!