-
Notifications
You must be signed in to change notification settings - Fork 0
/
naive_cnn.py
executable file
·96 lines (62 loc) · 2.03 KB
/
naive_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
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
import numpy as np
from keras import Sequential
from keras.layers import Conv2D, MaxPooling2D, ReLU, Dense, Flatten
from keras.optimizers import Adam
from util.model_base import ModelBase
def patchify(X):
patches = []
width = X.shape[0]
height = X.shape[1]
for y in range(0, height, 16):
for x in range(0, width, 16):
patches.append(X[x:x+16, y:y+16, :])
return patches
def patchify_gt(X):
patches = []
width = X.shape[0]
height = X.shape[1]
for y in range(0, height, 16):
for x in range(0, width, 16):
patches.append((np.mean(X[x:x+16, y:y+16]) >= 0.25) * 1)
return patches
def decompose(Y, X):
X_patches = []
Y_patches = []
for i in range(X.shape[0]):
X_patches += patchify(X[i])
Y_patches += patchify_gt(Y[i])
X_patches = np.array(X_patches)
Y_patches = np.array(Y_patches)
return Y_patches, X_patches
class NaiveConvModel(ModelBase):
def __init__(self):
self.model = None
def initialize(self):
layers = [
Conv2D(filters=32, kernel_size=5, input_shape=(16, 16, 3)),
ReLU(),
MaxPooling2D(pool_size=2),
Conv2D(filters=64, kernel_size=5),
ReLU(),
MaxPooling2D(pool_size=2),
Flatten(),
Dense(64),
ReLU(),
Dense(1, activation='sigmoid')
]
self.model = Sequential(layers)
def load(self, filename):
self.model.load_weights(filename)
def save(self, filename):
self.model.save_weights(filename)
def train(self, Y, X):
Y_f, X_f = decompose(Y, X)
self.model.summary()
self.model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])
self.model.fit(X_f, Y_f, batch_size=150, epochs=100)
def classify(self, X):
X_patches = []
for i in range(X.shape[0]):
X_patches += patchify(X[i])
Z = self.model.predict(np.array(X_patches))
return (Z >= 0.5) * 1