In [1]:
import pickle
pickle_file = '-catsdogs.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
X_train = save['X_train']
y_train = save['y_train']
X_test = save['X_test']
y_test = save['y_test']
del save # hint to help gc free up memory
print('Training set', X_train.shape, y_train.shape)
print('Test set', X_test.shape, y_test.shape)
In [2]:
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint
from keras import backend as K
from keras.datasets import mnist
In [3]:
# number of classes
num_classes = 2
# image dimensions
img_rows, img_cols = X_train.shape[1], X_train.shape[2]
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
Y_train = np_utils.to_categorical(y_train, num_classes)
Y_test = np_utils.to_categorical(y_test, num_classes)
print input_shape
In [4]:
# training parameters
batch_size = 16
nb_epoch = 30
# network architecture
patch_size_1 = 3
patch_size_2 = 3
patch_size_3 = 3
patch_size_4 = 3
depth_1 = 128
depth_2 = 256
depth_3 = 512
depth_4 = 1024
pool_size = 2
In [5]:
model = Sequential()
model.add(Convolution2D(depth_1, patch_size_1, patch_size_1, border_mode='valid',
input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))
model.add(Convolution2D(depth_2, patch_size_2, patch_size_2, border_mode='valid'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))
model.add(Convolution2D(depth_3, patch_size_3, patch_size_3, border_mode='valid'))
model.add(Activation('relu'))
# model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))
model.add(Convolution2D(depth_4, patch_size_4, patch_size_4, border_mode='valid'))
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=(10, 10)))
model.add(Flatten())
model.add(Dense(num_classes))
model.add(Activation('softmax'))
In [8]:
import os
checkpoint_name = "-model-CAM-2.hdf5"
if os.path.isfile(checkpoint_name):
model.load_weights(checkpoint_name)
checkpointer = ModelCheckpoint(checkpoint_name, verbose=0, save_best_only=True)
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy'])
In [ ]:
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test), callbacks=[checkpointer])
In [ ]: