How do you solve your own image classification problem with small labelled dataset
Let us use a self-collected small food picture dataset and see if we can classify them?
import numpy as np
import keras
import matplotlib.pyplot as plt
%matplotlib inline
# !wget http://bit.do/dosa-nodosa -O dosa.zip
# !unzip dosa.zip
from keras.preprocessing.image import load_img, img_to_array, array_to_img, ImageDataGenerator
img = load_img('food-binary/Dosa/img39.jpeg')
img_array = img_to_array(img)
img_array.shape
plt.imshow(img_array/255.);
We need to load the data from the file system
img_generator = ImageDataGenerator(validation_split=0.2, rescale=1.0/255)
def get_batches(path, subset, gen=img_generator, shuffle=True, batch_size=8, class_mode="categorical"):
return gen.flow_from_directory(path, target_size=(228,228), class_mode=class_mode,
shuffle=shuffle, batch_size=batch_size, subset=subset)
train_generator = get_batches('food-binary/', 'training')
val_generator = get_batches('food-binary/', 'validation')
train_generator.class_indices
from keras.applications import ResNet50
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten, GlobalAveragePooling2D
base_model = ResNet50(include_top=False, input_shape=(228,228,3))
#base_model.summary()
# Write the model in a functional way
x = base_model.output
x = GlobalAveragePooling2D()(x) #
x = Dense(128, activation="relu") (x) #
predictions = Dense(2, activation="softmax") (x)
m = Model(inputs=base_model.input, outputs=predictions)
#m.summary()
m.compile(loss="categorical_crossentropy", optimizer="sgd", metrics=["accuracy"])
m.fit_generator(
train_generator,
steps_per_epoch = 2000,
epochs=1,
validation_data = val_generator,
validation_steps=800
)