cnn from scratch with keras - code review





This post gives a working sample of training neutral net with cnn in keras.

CNN setup is based on Yan LeCun configuration.



model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))


model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])


validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')

test_datagen is of type ImageDataGenerator which helps with generating batches of tensor image. The function "flow_from_directory" - extracts sample test images from a directory.

Since this is a sample classifying cat and dog, we will use a binary classification / accuracy as shown in code above


To predict (check if our model works), we use the following code :-



img = load_img('dog.jpg',False,target_size=(img_width,img_height))
x = img_to_array(img)
x = np.expand_dims(x, axis=0)
preds = model.predict_classes(x)
probs = model.predict_proba(x)









Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm