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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| class CNN(object): """ 定义卷积神经网络模型 """
def __init__(self, classifiers=2, lr=1e-3, img_length=IMG_LENGTH, img_width=IMG_WIDTH): self.classifiers = classifiers self.lr = lr self.img_length = img_length self.img_width = img_width self.log_dir = 'log' self.model_name = 'dogsvscats-{}-{}.model'.format(lr, '6conv-basic')
tf.reset_default_graph() convnet = input_data(shape=[None, self.img_length, self.img_width, 1], name='input')
convnet = conv_2d(convnet, nb_filter=32, filter_size=5, activation='relu') convnet = max_pool_2d(convnet, kernel_size=5)
convnet = conv_2d(convnet, nb_filter=64, filter_size=5, activation='relu') convnet = max_pool_2d(convnet, kernel_size=5)
convnet = conv_2d(convnet, nb_filter=32, filter_size=2, activation='relu') convnet = max_pool_2d(convnet, 2)
convnet = conv_2d(convnet, nb_filter=64, filter_size=2, activation='relu') convnet = max_pool_2d(convnet, kernel_size=2)
convnet = conv_2d(convnet, nb_filter=32, filter_size=2, activation='relu') convnet = max_pool_2d(convnet, kernel_size=2)
convnet = conv_2d(convnet, nb_filter=64, filter_size=2, activation='relu') convnet = max_pool_2d(convnet, kernel_size=2)
convnet = fully_connected(convnet, n_units=1024, activation='relu')
convnet = dropout(convnet, keep_prob=0.5)
convnet = fully_connected(convnet, classifiers, activation='softmax') convnet = regression(convnet, optimizer='adam', learning_rate=self.lr, loss='categorical_crossentropy', name='targets')
self.network = tflearn.DNN(convnet, tensorboard_dir=self.log_dir)
def fit(self, train_dataset): train = train_dataset[:-2500] test = train_dataset[-2500:]
x = np.array([i[0] for i in train]).reshape(-1, self.img_length, self.img_width, 1) y = [i[1] for i in train]
test_x = np.array([i[0] for i in test]).reshape(-1, self.img_length, self.img_width, 1) test_y = [i[1] for i in test]
self.network.fit({'input': x}, {'targets': y}, n_epoch=5, validation_set=({'input': test_x}, {'targets': test_y}), snapshot_step=500, show_metric=True, run_id=self.model_name)
return self.network
def save(self): self.network.save(self.model_name)
return True
def load(self): if os.path.exists('{}.meta'.format(self.model_name)): self.network.load(self.model_name) print "model loaded!" return self.network else: print "no existed model, need training" return False
def predict(self, dataset): if 0 < len(dataset) <= 12: fig = plt.figure()
for num, data in enumerate(dataset): img_data = data[0] img_index = data[1]
y = fig.add_subplot(3, 4, num + 1) orig = img_data data = img_data.reshape(self.img_length, self.img_width, 1)
model_out = self.network.predict([data])[0]
if np.argmax(model_out) == 1: str_label = 'Dog-' + img_index else: str_label = 'Cat-' + img_index
y.imshow(orig, cmap='gray') plt.title(str_label) y.axes.get_xaxis().set_visible(False) y.axes.get_yaxis().set_visible(False)
plt.show() else: with open('result.csv', 'w') as f: f.write('id,label\n')
with open('result.csv', 'a') as f: for data in tqdm(dataset): img_num = data[1] img_data = data[0] data = img_data.reshape(self.img_length, self.img_width, 1) model_out = self.network.predict([data])[0]
f.write('{},{}\n'.format(img_num, model_out[1])) print "Result show in file result.csv"
|