Skip to content

Instantly share code, notes, and snippets.

@aaronpolhamus
Created April 1, 2016 22:42
Show Gist options
  • Save aaronpolhamus/034cfe4dd8e2cc26ccb24ad6616bf7b4 to your computer and use it in GitHub Desktop.
Save aaronpolhamus/034cfe4dd8e2cc26ccb24ad6616bf7b4 to your computer and use it in GitHub Desktop.
Adaptation of VGG net for Keras, with 128x128 greyscale images and 196 target classes
import os
import sys
import json
import model_control
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
import numpy as np
from numpy import loadtxt, asarray
from scipy.ndimage import imread
Y_train = loadtxt(model_control.y_train_file, delimiter=',', dtype = int)
train_files = os.listdir(model_control.train_img_path)
train_files = ['%s/%s' % (model_control.train_img_path, x) for x in train_files if 'jpg' in x]
X_train = asarray([imread(x) for x in train_files])
X_train = X_train.reshape(X_train.shape[0], 1, 128, 128)
model = Sequential()
model.add(Convolution2D(64, 3, 3, border_mode='valid', input_shape=(1, 128, 128)))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Convolution2D(128, 3, 3))
model.add(Activation('relu'))
model.add(Convolution2D(128, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Convolution2D(256, 3, 3))
model.add(Activation('relu'))
model.add(Convolution2D(256, 3, 3))
model.add(Activation('relu'))
model.add(Convolution2D(256, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Convolution2D(512, 3, 3))
model.add(Activation('relu'))
model.add(Convolution2D(512, 3, 3))
model.add(Activation('relu'))
model.add(Convolution2D(512, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(2000))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2000))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(196, activation='softmax'))
sgd = SGD(lr=model_control.l_rate, decay=0, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)
history = model.fit(X_train, Y_train, batch_size=model_control.batch_size, nb_epoch=model_control.nb_epoch, verbose=1)
model.save_weights('vgg_net_weights.h5')
json_string = model.to_json()
with open('vgg_net_structure.json', 'wb') as outfile:
json.dump(json_string, outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment