This repository has been archived by the owner on Aug 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Autoencoder1.py
93 lines (75 loc) · 2.28 KB
/
Autoencoder1.py
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
##########Autoencoder##############
### using Keras on MNIST data
import keras
# import tensorflow
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras import backend as K
(x_train, y_train), (x_test, y_test) = mnist.load_data()
img_rows, img_cols = 28, 28
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
import numpy as np
temp = []
for img in x_train:
t = []
for row in img:
for i in row:
t.append(i)
temp.append(t)
x_train = []
x_train = temp
x_train = np.array(x_train)
x_train = x_train.reshape(60000,784)
model = Sequential()
model.add(Dense(784,activation='relu',input_dim=784))
model.add(Dense(256,activation='relu'))
model.add(Dense(128,activation='relu'))
model.add(Dense(256,activation='relu'))
model.add(Dense(784,activation='relu'))
model.compile(loss=keras.losses.mean_squared_error,
optimizer=keras.optimizers.RMSprop(lr=0.0001, rho=0.9, epsilon=None, decay=0.0),
metrics = ['accuracy'])
model.fit(x_train,x_train,verbose=1,epochs=5,batch_size=200)
model.save('auto_en.h5')
#del model
from keras.models import load_model
import cv2
model = load_model('auto_en.h5')
test = x_train[1].reshape(1,784)
y_test = model.predict(test)
for j in range(len(test)):
inp_img = []
temp = []
for i in range(len(test[j])):
if((i+1)%28 == 0):
temp.append(test[j][i])
inp_img.append(temp)
temp = []
else:
temp.append(test[j][i])
out_img = []
temp = []
for i in range(len(y_test[j])):
if((i+1)%28 == 0):
temp.append(y_test[j][i])
out_img.append(temp)
temp = []
else:
temp.append(y_test[0][i])
inp_img = np.array(inp_img)
out_img = np.array(out_img)
cv2.imshow('Test Image',inp_img)
cv2.imshow('Output Image',out_img)
cv2.waitKey(15)