第三讲 神经网络八股--Fashion Mnist数据集分类

 1 import tensorflow as tf
 2 
 3 fashion = tf.keras.datasets.fashion_mnist
 4 (x_train, y_train), (x_test, y_test)  = fashion.load_data()
 5 
 6 print(x_train.shape, y_train.shape)
 7 print(x_test.shape, y_test.shape)
 8 print(x_train[0])
 9 print(y_train[0])
10 
11 x_train, x_test = x_train/255.0, x_test/255.0
12 
13 model = tf.keras.models.Sequential([
14         tf.keras.layers.Flatten(),
15         tf.keras.layers.Dense(128, activation='relu'),
16         tf.keras.layers.Dense(10, activation='softmax')
17 ])
18 
19 model.compile(optimizer='adam',
20               loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
21               metrics=['sparse_categorical_accuracy'])
22 
23 model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
24 model.summary()
25 
26 
27 
28 
29 
30 import tensorflow as tf
31 from tensorflow.keras.layers import Flatten, Dense
32 from tensorflow.keras import Model
33 
34 fashion = tf.keras.datasets.fashion_mnist
35 (x_train, y_train), (x_test, y_test)  = fashion.load_data()
36 x_train, x_test = x_train/255.0, x_test/255.0
37 
38 class FashionModel(Model):
39   def __init__(self):
40     super(FashionModel, self).__init__()
41     self.flatten = Flatten()
42     self.d1 = Dense(128, activation='relu')
43     self.d2 = Dense(10, activation='softmax')
44 
45   def call(self, x):
46     x = self.flatten(x)
47     x = self.d1(x)
48     y = self.d2(x)
49     return y
50 
51 
52 model = FashionModel()
53 
54 model.compile(optimizer = 'adam', 
55               loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
56               metrics=['sparse_categorical_accuracy'])
57 
58 model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
59 model.summary()

 

posted @ 2020-05-04 23:05  WWBlog  阅读(383)  评论(0编辑  收藏  举报