Skip to content

Commit 93e469f

Browse files
authored
updated 10.22
1 parent 4c9bad0 commit 93e469f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#%% md
2+
3+
我们在“线性回归的简洁实现”一节中已经了解了使用tensorflow2.0实现模型的便利。下面,让我们再次使用Gluon来实现一个softmax回归模型。首先导入所需的包或模块。
4+
5+
#%%
6+
7+
import tensorflow as tf
8+
9+
#%% md
10+
11+
3.7.1. 获取和读取数据¶
12+
我们仍然使用Fashion-MNIST数据集和上一节中设置的批量大小。
13+
14+
#%%
15+
16+
from tensorflow import keras
17+
fashion_mnist = keras.datasets.fashion_mnist
18+
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
19+
20+
#%% md
21+
22+
对数据进行处理,归一化,便于训练
23+
24+
#%%
25+
26+
x_train = x_train / 255.0
27+
x_test = x_test / 255.0
28+
29+
#%% md
30+
31+
在“softmax回归”一节中提到,softmax回归的输出层是一个全连接层。因此,我们添加一个输出个数为10的全连接层。
32+
第一层是Flatten,将28 * 28的像素值,压缩成一行 (784, )
33+
第二层还是Dense,因为是多分类问题,激活函数使用softmax
34+
35+
#%%
36+
37+
from tensorflow import keras
38+
model = keras.Sequential([
39+
keras.layers.Flatten(input_shape=(28, 28)),
40+
keras.layers.Dense(10, activation=tf.nn.softmax)
41+
])
42+
43+
#%% md
44+
45+
使用交叉熵损失函数和学习率为0.1的小批量随机梯度下降作为优化算法对模型进行训练
46+
47+
#%%
48+
49+
model.compile(optimizer=tf.keras.optimizers.SGD(0.1),
50+
loss = 'sparse_categorical_crossentropy',
51+
metrics=['accuracy'])
52+
53+
#%% md
54+
55+
选用batch的大小为256,对模型进行训练
56+
57+
#%%
58+
59+
model.fit(x_train,y_train,epochs=5,batch_size=256)
60+
61+
#%% md
62+
63+
接下来,比较模型在测试数据集上的表现情况
64+
65+
#%%
66+
67+
test_loss, test_acc = model.evaluate(x_test, y_test)
68+
print('Test Acc:',test_acc)
69+
70+
#%%
71+
72+

0 commit comments

Comments
 (0)