Skip to content

Instantly share code, notes, and snippets.

@spirosrap
Last active July 26, 2017 22:09
Show Gist options
  • Save spirosrap/4c96df967aeca03dbf1e8341a714d68e to your computer and use it in GitHub Desktop.
Save spirosrap/4c96df967aeca03dbf1e8341a714d68e to your computer and use it in GitHub Desktop.
Generate VGG16 model for CoreML
# Modified from https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3#file-vgg-16_keras-py
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
import cv2, numpy as np
from keras import backend as K
import csv
import coremltools
from keras import models
import sys
import imghdr
import os.path
def VGG_16(weights_path=None):
model = Sequential()
model.add(ZeroPadding2D((1,1),input_shape=(3,224,224)))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(128, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(128, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1000, activation='softmax'))
if weights_path:
model.load_weights(weights_path)
return model
if __name__ == "__main__":
K.set_image_dim_ordering('th')
## Check if there input filename exists
if os.path.exists(sys.argv[1]) == False:
print("Please enter a valid filename")
exit()
input_image = cv2.imread(sys.argv[1])
img = cv2.resize(input_image, (224, 224)).astype(np.float32)
mean_pixel = [103.939, 116.779, 123.68]
img = img.astype(np.float32, copy=False)
for c in range(3):
img[:, :, c] = img[:, :, c] - mean_pixel[c]
img = img.transpose((2,0,1))
img = np.expand_dims(img, axis=0)
# Test pretrained model
model = VGG_16('vgg16_weights.h5')
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy')
out = model.predict(img)
line = np.argmax(out)
the_file = open('synset_words.txt', 'r')
reader = csv.reader(the_file)
for i, row in enumerate(reader):
if i == line:
print(row)
break
models.save_model(model,'vgg16.h5')
### Uncomment if you want to generate the .mlmodel file for Xcode
# coreml_model = coremltools.converters.keras.convert('vgg16.h5')
# coreml_model.save('vgg16_keras.mlmodel')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment