-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain_Images.py
81 lines (66 loc) · 2.58 KB
/
Main_Images.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
import os
import random
import matplotlib.pyplot as plt
import numpy as np
from Model import Autoencoder
projectDir = os.path.dirname(os.path.realpath(__file__))
learningRate = 0.001
batchSize = 250
numEpochs = 10000
denoise = True
step = 50
newModel = True
# trainImages = np.loadtxt(projectDir + "/Data/Images/fashion-mnist_train.csv", delimiter=',', skiprows=1)[:, 1:]
# testImages = np.loadtxt(projectDir + "/Data/Images/fashion-mnist_test.csv", delimiter=',', skiprows=1)[:, 1:]
trainImages = np.loadtxt(projectDir + "/Data/MNIST/emnist-mnist-train.csv", delimiter=',', skiprows=1)[:, 1:]
testImages = np.loadtxt(projectDir + "/Data/MNIST/emnist-mnist-test.csv", delimiter=',', skiprows=1)[:, 1:]
numTrain = len(trainImages)
numTest = len(testImages)
numTrainBatches = numTrain // batchSize
numTestBatches = numTest // batchSize
imgW = imgH = 28
encoderDims = [
imgW * imgH,
(imgW // 2) * (imgH // 2),
(imgW // 3) * (imgH // 3),
(imgW // 4) * (imgH // 4) # Last dim must be a square number
]
codeW = codeH = int(np.sqrt(encoderDims[-1]))
ae = Autoencoder(encoderDims, denoise=denoise)
bestLoss = 9999
if not newModel:
ae.restore()
for epoch in range(numEpochs):
epochLoss = 0
for batch in range(numTrainBatches):
batchInput = trainImages[batch * batchSize: (batch + 1) * batchSize]
ae.setBatch(batchInput, learningRate)
batchLoss = ae.run(['loss'], train=True)
epochLoss += batchLoss
epochLoss /= numTrainBatches
print("EPOCH:", epoch + 1)
print("LOSS: ", epochLoss, "\n")
if epochLoss < bestLoss:
ae.save()
if epoch % step == 0:
testLoss = 0
for batch in range(numTestBatches):
batchInput = testImages[batch * batchSize: (batch + 1) * batchSize]
ae.setBatch(batchInput)
batchLoss = ae.run(['loss'])
testLoss += batchLoss
testLoss /= numTestBatches
print("TEST LOSS: ", testLoss, "\n")
rand = random.randint(0, numTest - 1)
ae.setBatch([testImages[rand]])
original, compressed, reconstructed = \
ae.run(['noisyInput', 'encoded', 'decoded'], train=False)
plt.imshow(original.reshape(imgW, imgH), cmap='Greys')
plt.savefig(projectDir + "/Data/Images/originalTest.png")
plt.clf()
plt.imshow(compressed.reshape(codeW, codeH), cmap='Greys')
plt.savefig(projectDir + "/Data/Images/compressedTest.png")
plt.clf()
plt.imshow(reconstructed.reshape(imgW, imgH), cmap='Greys')
plt.savefig(projectDir + "/Data/Images/reconstructedTest.png")
plt.clf()