-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto-encoder
158 lines (124 loc) · 4.3 KB
/
auto-encoder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import matplotlib
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
from IPython.display import SVG
import matplotlib.pyplot as plt
print(tf.__version__)
# load data
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
type(x_test)
x_train[0]
plt.imshow(x_train[0])
# select the first 1000 pieces of data
x_train = x_train[ : 1000, ]
y_train = y_train[ : 1000, ]
x_test = x_test[ : 1000, ]
y_test = y_test[ : 1000, ]
# normalization
x_train = x_train.reshape((-1, 28*28)) / 255.0
x_test = x_test.reshape((-1, 28*28)) / 255.0
print(x_train.shape, ' ', y_train.shape)
print(x_test.shape, ' ', y_test.shape)
# construction of auto-encoder
inputs = layers.Input(shape = (x_train.shape[1], ), name = 'inputs')
code_dim = 100
code = layers.Dense(code_dim, activation = 'relu', name = 'code')(inputs)
outputs = layers.Dense(x_train.shape[1], activation = 'sigmoid', name = 'outputs')(code)
auto_encoder = keras.Model(inputs, outputs, name = 'auto_encoder')
auto_encoder.summary()
# visualization
keras.utils.plot_model(auto_encoder, show_shapes = True)
encoder = keras.Model(inputs, code) #encoder
keras.utils.plot_model(encoder, show_shapes = True)
decoder_input = keras.Input((code_dim, ), name = 'decoder_input')
decoder_output = auto_encoder.layers[-1](decoder_input)
decoder = keras.Model(decoder_input, decoder_output, name = 'decoder') #decoder
decoder.summary()
decoder = keras.Model(decoder_input, decoder_output)
keras.utils.plot_model(decoder, show_shapes = True)
# Configuration training method
auto_encoder.compile(optimizer = tf.keras.optimizers.Adam(lr = 0.005),
loss = 'binary_crossentropy',
metrics = ['binary_accuracy'])
# training model
%%time
history = auto_encoder.fit(x_train, x_train,
batch_size = 128,
validation_split = 0.1,
epochs = 100)
# evaluate
auto_encoder.evaluate(x_test, x_test)
# visualization
plt.figure(figsize = (16, 6))
plt.rcParams["savefig.dpi"] = 300
plt.rcParams["figure.dpi"] = 300
plt.subplot(1, 2, 1)
plt.plot(history.epoch, history.history.get('loss'))
plt.xlabel('epoch', fontsize = 14)
plt.ylabel('binary_crossentropy', fontsize = 14)
plt.subplot(1, 2, 2)
plt.plot(history.epoch, history.history.get('binary_accuracy'))
plt.xlabel('epoch', fontsize = 14)
plt.ylabel('binary_accuracy', fontsize = 14)
plt.savefig("1.png", dpi = 300)
# predict
## in training set
encoded = encoder.predict(x_train)
decoded = decoder.predict(encoded)
print(encoded[0], '\n', encoded.shape)
print(decoded[0], '\n', decoded.shape)
plt.figure(figsize = (16, 6))
plt.rcParams["savefig.dpi"] = 300
plt.rcParams["figure.dpi"] = 300
n = 5
for i in range(n):
ax = plt.subplot(3, n, i+1)
plt.imshow(x_train[i].reshape(28, 28))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, n+i+1)
plt.imshow(encoded[i].reshape(10, 10))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, 2*n+i+1)
plt.imshow(decoded[i].reshape(28, 28))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
plt.savefig("2.png", dpi = 300)
## in test set
encoded = encoder.predict(x_test)
decoded = decoder.predict(encoded)
plt.figure(figsize = (16, 6))
plt.rcParams["savefig.dpi"] = 300
plt.rcParams["figure.dpi"] = 300
n = 5
for i in range(n):
ax = plt.subplot(3, n, i+1)
plt.imshow(x_test[i].reshape(28, 28))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, n+i+1)
plt.imshow(encoded[i].reshape(10, 10))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(3, n, 2*n+i+1)
plt.imshow(decoded[i].reshape(28, 28))
#plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
plt.savefig("3.png", dpi = 300)
# save data
auto_encoder.save('./auto_encoder.h5')
auto_encoder.save_weights('./auto_encoder_weights.h5')
np.savetxt('./code.txt', encoded)