Skip to content

Instantly share code, notes, and snippets.

@rouseguy
Created July 24, 2018 04:11
Show Gist options
  • Save rouseguy/1bb4ef5e2876e7634f73967a5772f36b to your computer and use it in GitHub Desktop.
Save rouseguy/1bb4ef5e2876e7634f73967a5772f36b to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import keras\n",
"from keras.preprocessing.image import load_img, img_to_array, array_to_img, ImageDataGenerator\n",
"from keras.models import Sequential, Model\n",
"from keras.layers import Conv2D, MaxPooling2D\n",
"from keras.layers import Activation, Dropout, Flatten, Dense, GlobalAveragePooling2D\n",
"from keras.callbacks import ModelCheckpoint\n",
"from keras.applications import ResNet50\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"img = load_img('food-binary/Dosa/img39.jpeg')\n",
"x = img_to_array(img)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.imshow(x/255.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"img_generator = ImageDataGenerator(rotation_range=90.,\n",
" featurewise_center=True, \n",
" horizontal_flip=True,\n",
" fill_mode='reflect',\n",
" vertical_flip=True,\n",
" zoom_range=0.4,\n",
" featurewise_std_normalization=True,\n",
" width_shift_range=20,\n",
" height_shift_range=20,\n",
" validation_split=0.2, rescale=1./255)\n",
"\n",
"def get_batches(path, subset, gen=img_generator, \n",
" shuffle=True, batch_size=8, class_mode='categorical'): \n",
" return gen.flow_from_directory(path, target_size=(228,228), \n",
" class_mode=class_mode, shuffle=shuffle, batch_size=batch_size, subset=subset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Data Augmentation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"img = load_img('food-binary/Dosa/img101.jpeg') \n",
"x = img_to_array(img) \n",
"x = x.reshape((1,) + x.shape) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pwd"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# create preview folder"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"i = 0\n",
"for batch in img_generator.flow(x, batch_size=1,\n",
" save_to_dir='preview', save_prefix='cat', save_format='jpeg'):\n",
" i += 1\n",
" if i > 20:\n",
" break # otherwise the generator would loop indefinitely"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Check images in preview folder"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Transfer Learning with Image Augmentation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from keras.applications import ResNet50"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_generator = get_batches('food-binary/', 'training')\n",
"val_generator = get_batches('food-binary/', 'validation')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"base_model = ResNet50(include_top=False, input_shape=(228,228,3))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"batch_size=28"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = base_model.output\n",
"x = GlobalAveragePooling2D()(x)\n",
"x = Dense(128, activation='relu')(x)\n",
"predictions = Dense(2, activation='softmax')(x)\n",
"m = Model(inputs=base_model.input, outputs=predictions)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# m.summary()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.compile(loss='categorical_crossentropy',\n",
" optimizer='sgd',\n",
" metrics=['accuracy'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"m.fit_generator(\n",
" train_generator,\n",
" steps_per_epoch=2000 // batch_size,\n",
" epochs=1,\n",
" validation_data=val_generator,\n",
" validation_steps=800 // batch_size)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment