4
4
# @Software: PyCharm
5
5
# pip install --upgrade --ignore-installed tensorflow
6
6
import matplotlib as mpl
7
+ import os
7
8
import matplotlib .pyplot as plt
8
9
import numpy as np
9
10
import tensorflow as tf
11
+ import pandas as pd
10
12
from tensorflow import keras
13
+ from sklearn .preprocessing import StandardScaler
11
14
12
15
fashion_mnist = keras .datasets .fashion_mnist
13
16
# 共六万图片
14
17
(x_train_all , y_train_all ), (x_test , y_test ) = fashion_mnist .load_data ()
15
18
x_valid , x_train = x_train_all [:5000 ], x_train_all [5000 :]
16
19
y_valid , y_train = y_train_all [:5000 ], y_train_all [5000 :]
17
20
21
+ print (np .max (x_train ), np .min (x_train ))
22
+
23
+ # 做归一化
24
+ scaler = StandardScaler ()
25
+ x_train_scaled = scaler .fit_transform (x_train .astype (np .float32 ).reshape (- 1 , 1 )).reshape (- 1 , 28 , 28 )
26
+
27
+ x_valid_scaled = scaler .transform (x_valid .astype (np .float32 ).reshape (- 1 , 1 )).reshape (- 1 , 28 , 28 )
28
+
29
+ x_test_scaled = scaler .transform (x_test .astype (np .float32 ).reshape (- 1 , 1 )).reshape (- 1 , 28 , 28 )
30
+
31
+ print (np .max (x_train_scaled ), np .min (x_train_scaled ))
32
+
18
33
print (x_valid .shape , y_valid .shape )
19
34
print (x_train .shape , y_train .shape )
20
35
print (x_test .shape , y_test .shape )
@@ -35,15 +50,68 @@ def show_images(n_rows, n_cols, x_data, y_data, class_names):
35
50
plt .figure (figsize = (n_cols * 1.4 , n_rows * 1.6 ))
36
51
for row in range (n_rows ):
37
52
for col in range (n_cols ):
38
- index = n_cols * n_rows + col
39
- plt .subplot (n_rows , n_cols , index + 1 )
53
+ # index 表示在n_rows行 n_cols列中的 哪个地方画图 取值范围为1,n_rows*n_cols
54
+ index = n_rows * n_cols - col - row * n_cols
55
+ plt .subplot (n_rows , n_cols , index )
40
56
plt .imshow (x_data [index ], cmap = "binary" , interpolation = "nearest" )
41
57
plt .axis ("off" )
42
58
plt .title (class_names [y_data [index ]])
43
59
44
60
plt .show ()
45
61
46
62
63
+ def train ():
64
+ models = keras .models .Sequential ()
65
+ # 输入28*28的图像数据 28*28的矩阵变为 1*726的一维向量
66
+ models .add (keras .layers .Flatten (input_shape = [28 , 28 ]))
67
+ # 全连接层 relu激活函数
68
+ models .add (keras .layers .Dense (300 , activation = "relu" ))
69
+
70
+ models .add (keras .layers .Dense (100 , activation = "relu" ))
71
+
72
+ # softmax将向量变成概率分布
73
+ # x= [x1,x2,x3]
74
+ # y = [e^x1/sum,e^x2/sum,e^x3/sum],sum = e^x1+e^x2+e^x3
75
+ models .add (keras .layers .Dense (10 , activation = "softmax" ))
76
+
77
+ models .compile (loss = "sparse_categorical_crossentropy" ,
78
+ optimizer = "sgd" ,
79
+ metrics = ["accuracy" ])
80
+
81
+ # 模型的层
82
+ print (models .layers )
83
+
84
+ # 可以看到模型的参数
85
+ print (models .summary ())
86
+
87
+ # TensorBoard earlytopping ModelCheckpoint
88
+
89
+ log_dir = "callbacks"
90
+ if not os .path .exists (log_dir ):
91
+ os .mkdir (log_dir )
92
+ ouput_model_file = os .path .join (log_dir , "fashion_mnist.h5" )
93
+
94
+ callbacks = [
95
+ keras .callbacks .TensorBoard (log_dir ),
96
+ keras .callbacks .ModelCheckpoint (ouput_model_file , save_best_only = True ),
97
+ keras .callbacks .EarlyStopping (patience = 5 , min_delta = 1e-3 ),
98
+ ]
99
+ history = models .fit (x_train_scaled , y_train , epochs = 20 , validation_data = (x_valid_scaled , y_valid ),
100
+ callbacks = callbacks )
101
+
102
+ # 测试集上评估
103
+ print (models .evaluate (x_test_scaled , y_test ))
104
+
105
+ # 存储训练过程中的一些值 如损失 accury等
106
+ print (history .history )
107
+
108
+ pd .DataFrame (history .history ).plot (figsize = (8 , 5 ))
109
+ plt .grid (True )
110
+ plt .gca ().set_ylim (0 , 1 )
111
+ plt .show ()
112
+
113
+
47
114
if __name__ == '__main__' :
48
- show_single_image (x_train [0 ])
49
- # show_images(1,1,x_train,y_train,class_names)
115
+ train ()
116
+ # show_single_image(x_train[0])
117
+ # show_images(10,5,x_train,y_train,class_names)
0 commit comments