forked from neokarn/computer_vision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example7_1_CNN.py
70 lines (55 loc) · 1.76 KB
/
example7_1_CNN.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
from keras.models import Model
from keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
import cv2
#Create model
input = Input(shape = (50,50,1))
conv1 = Conv2D(8,3,activation='relu')(input)
pool1 = MaxPool2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(8,3,activation='relu')(pool1)
pool2 = MaxPool2D(pool_size=(2, 2))(conv2)
flat = Flatten()(pool2)
hidden = Dense(16, activation='relu')(flat)
output = Dense(3, activation='softmax')(hidden)
model = Model(inputs=input, outputs=output)
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
#Read data from file
N = 30
x_train = np.zeros((N,50,50,1),'float')
y_train = np.zeros((N),'float')
count = 0
for class_id in range(1,4):
for im_id in range(1,11):
im = cv2.imread("thainum123/train/"+str(class_id)+"/"+str(im_id)+".bmp",cv2.IMREAD_GRAYSCALE)
im = cv2.resize(im,(50,50))
x_train[count,:,:,0] = im/255.
y_train[count] = class_id-1
count += 1
y_train = to_categorical(y_train)
#Train Model
h = model.fit(x_train, y_train, epochs=20)
plt.plot(h.history['acc'])
plt.show()
#Test Model
N = 15
x_test = np.zeros((N,50,50,1),'float')
y_test = np.zeros((N),'float')
count = 0
for class_id in range(1,4):
for im_id in range(1,6):
im = cv2.imread("thainum123/test/"+str(class_id)+"/"+str(im_id)+".bmp",cv2.IMREAD_GRAYSCALE)
im = cv2.resize(im,(50,50))
x_test[count,:,:,0] = im/255.
y_test[count] = class_id-1
count += 1
y_test = to_categorical(y_test)
score = model.evaluate(x_test, y_test)
print(score)
y_pred = model.predict(x_test)
print(y_pred)
print(np.argmax(y_pred,axis = -1)+1)