Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
transfer learning VGG16
import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
%matplotlib inline
#Path to folders
train_path = 'data/train'
valid_path = 'data/validation'
#Preparing images for VGG16
train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224,224), classes=['burger','cat'], batch_size=10)
valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(224,224), classes=['burger','cat'], batch_size=4)
#Give a visual representation of labels and images asociated
def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):
if type(ims[0]) is np.ndarray:
ims = np.array(ims).astype(np.uint8)
if(ims.shape[-1] != 3):
ims = ims.transpose((0,2,3,1))
f = plt.figure(figsize=figsize)
cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows+1
for i in range(len(ims)):
sp = f.add_subplot(rows, cols,i+1)
sp.axis('Off')
if titles is not None:
sp.set_title(titles[i], fontsize=16)
plt.imshow(ims[i], interpolation=None if interp else 'none')
#Show Images
imgs, labels = next(train_batches)
plots(imgs, titles=labels)
#Get VGG16 model, and deleting last layer
vgg16_model = keras.applications.vgg16.VGG16()
model = Sequential()
for layer in vgg16_model.layers[:-1]:
model.add(layer)
#Freeze all layers
for layer in model.layers:
layer.trainable = False
#Add layer for predictions, and activation
model.add(Dense(2, activation='softmax'))
#Our learning rate, and loss method
model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])
# TRAIN TIME!
model.fit_generator(train_batches, steps_per_epoch=4, validation_data=valid_batches, validation_steps=4, epochs=20, verbose=1)
#Function for predictions
def predict(file):
x = load_img(file, target_size=(224,224))
x = img_to_array(x)
x = np.expand_dims(x, axis=0)
array = model.predict( x, batch_size=14, verbose=1)
#result = array[0]
#answer = np.argmax(result)
return array
#Predict!
predict('./burger2.jpg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment