-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnnTrain.py
102 lines (94 loc) · 3.51 KB
/
cnnTrain.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
93
94
95
96
97
98
99
100
101
102
import cnnModel
import os
os.environ['KERAS_BACKEND'] = 'theano'
from keras import backend
import numpy as np
from PIL import Image
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
backend.common.set_image_dim_ordering('th')
model = None
path = ""
no_epoch = 70
batch_size = 64
def trainModel():
global model,path
model = cnnModel.createCNNModel(-1)
no_classes = cnnModel.no_classes
img_x = cnnModel.img_x
img_y = cnnModel.img_y
img_channels = cnnModel.img_channels
dataSetType = int(input("Enter 1 for Adaptive Threshold Mode Dataset \nEnter 2 for Sift Mode Dataset \nEnter 3 for No Filter Mode Dataset\n"))
if dataSetType == 1:
path = './AdaptiveThresholdModeDataSet'
elif dataSetType == 2:
path = './SiftModeDataSet'
elif dataSetType == 3:
path = './NoFilterModeDataSet'
#create dataset array
listing = os.listdir(path)
listing.sort()
dataset = []
for name in listing:
dataset.append(name)
image = np.array(Image.open(path +'/' + dataset[0]))
#fnd size of image
m,n = image.shape[0:2]
#find dataset size
dataset_size = len(dataset)
# create matrix to store all flattened images
image_matrix = np.array([np.array(Image.open(path+ '/' + images).convert('L')).flatten() for images in dataset], dtype = 'f')
label=np.ones((dataset_size,),dtype = int)
samples_per_class = dataset_size / no_classes
s = 0
r = samples_per_class
for classIdentifier in range(no_classes):
label[int(s):int(r)] = classIdentifier
s = r
r = s + samples_per_class
data,Label = shuffle(image_matrix,label, random_state=2)
train_data = [data,Label]
(X, y) = (train_data[0],train_data[1])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=4)
X_train = X_train.reshape(X_train.shape[0], img_channels, img_x, img_y)
X_test = X_test.reshape(X_test.shape[0], img_channels, img_x, img_y)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
Y_train = np_utils.to_categorical(y_train, no_classes)
Y_test = np_utils.to_categorical(y_test, no_classes)
history = model.fit(X_train, Y_train, batch_size=batch_size, epochs=no_epoch,verbose=1, validation_split=0.25)
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
if dataSetType == 1:
model.save_weights("./adaptivethresholdmodeweight.hdf5",overwrite=True)
elif dataSetType == 2:
model.save_weights("./siftmodeweight.hdf5",overwrite=True)
elif dataSetType == 3:
model.save_weights("./nofiltermodeweight.hdf5",overwrite=True)
print(history.history.keys())
print(history.history.keys())
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('acc.png')
plt.close('all')
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('loss.png')
plt.close('all')
print("Model trained successfully")
trainModel()