Last active
January 30, 2018 09:18
-
-
Save blackredscarf/2e81c804151d5346261f6752807a75ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# In[18]: | |
import numpy as np | |
from keras import layers | |
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D | |
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D | |
from keras.models import Model | |
from keras.preprocessing import image | |
from keras.utils import layer_utils | |
from keras.utils.data_utils import get_file | |
from keras.applications.imagenet_utils import preprocess_input | |
import pydot | |
import keras | |
from IPython.display import SVG | |
from keras.utils.vis_utils import model_to_dot | |
from keras.utils import plot_model | |
from keras.applications.mobilenet import MobileNet | |
import matplotlib.pyplot as plt | |
get_ipython().run_line_magic('matplotlib', 'inline') | |
import keras.backend as K | |
K.set_image_data_format('channels_last') | |
K.set_learning_phase(1) | |
from keras.models import model_from_json | |
from keras.utils.generic_utils import CustomObjectScope | |
# In[35]: | |
def myPredict(img_path, model): | |
img = image.load_img(img_path, target_size=(128, 128)) | |
x = image.img_to_array(img) | |
x = np.expand_dims(x, axis=0) | |
x = preprocess_input(x) | |
return model.predict(x)[0] | |
# In[28]: | |
import tensorflow as tf | |
from keras.backend.tensorflow_backend import set_session | |
config = tf.ConfigProto() | |
config.gpu_options.allow_growth=True | |
set_session(tf.Session(config=config)) | |
# In[30]: | |
from keras.models import load_model | |
model = load_model('flower_model.h5', custom_objects={ | |
'relu6': keras.applications.mobilenet.relu6, | |
'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}) | |
# In[36]: | |
preds = myPredict("test-tulips.jpg", model) | |
result = np.array(preds).argmax() | |
print(result) # ans: 1 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# In[1]: | |
import numpy as np | |
from keras import layers | |
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D | |
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D | |
from keras.models import Model | |
from keras.preprocessing import image | |
from keras.utils import layer_utils | |
from keras.utils.data_utils import get_file | |
from keras.applications.imagenet_utils import preprocess_input | |
import pydot | |
from IPython.display import SVG | |
from keras.utils.vis_utils import model_to_dot | |
from keras.utils import plot_model | |
import tensorflow as tf | |
from keras.backend.tensorflow_backend import set_session | |
config = tf.ConfigProto() | |
config.gpu_options.allow_growth=True | |
set_session(tf.Session(config=config)) | |
# In[2]: | |
train_dir = "flower_photos_small/train" | |
test_dir = "flower_photos_small/test" | |
IM_WIDTH = 128 | |
IM_HEIGHT = 128 | |
batch_size = 36 | |
# In[3]: | |
from keras.preprocessing.image import ImageDataGenerator | |
train_datagen = ImageDataGenerator( | |
preprocessing_function=preprocess_input, | |
rotation_range=30, | |
width_shift_range=0.2, | |
height_shift_range=0.2, | |
shear_range=0.2, | |
zoom_range=0.2, | |
horizontal_flip=True | |
) | |
test_datagen = ImageDataGenerator( | |
preprocessing_function=preprocess_input, | |
rotation_range=30, | |
width_shift_range=0.2, | |
height_shift_range=0.2, | |
shear_range=0.2, | |
zoom_range=0.2, | |
horizontal_flip=True | |
) | |
train_generator = train_datagen.flow_from_directory( | |
train_dir, | |
target_size=(IM_WIDTH, IM_HEIGHT), | |
batch_size=batch_size, | |
) | |
validation_generator = test_datagen.flow_from_directory( | |
test_dir, | |
target_size=(IM_WIDTH, IM_HEIGHT), | |
batch_size=batch_size, | |
) | |
# In[4]: | |
from keras.applications.mobilenet import MobileNet | |
base_model = MobileNet(weights='imagenet', include_top=False, input_shape=(128, 128, 3)) | |
# In[5]: | |
base_model.summary() | |
# In[6]: | |
def add_new_layer(base_model, classes): | |
x = base_model.output | |
x = GlobalAveragePooling2D()(x) | |
x = Dense(36, activation='relu')(x) | |
predictions = Dense(classes, activation='softmax')(x) | |
model = Model(input=base_model.input, output=predictions) | |
return model | |
# In[7]: | |
model = add_new_layer(base_model, 5) | |
base_model.trainable = False | |
model.compile(optimizer='adam', | |
loss='categorical_crossentropy', | |
metrics=['accuracy']) | |
# In[8]: | |
history = model.fit_generator( | |
train_generator, | |
steps_per_epoch=100, | |
epochs=20, | |
validation_data=validation_generator, | |
validation_steps=30) | |
# In[9]: | |
model.save("flower_model.h5") | |
# In[10]: | |
model.save_weights("flower_model_weights.h5") | |
# In[11]: | |
jsonstr = model.to_json() | |
f = open("flower_model_json.json", "w") | |
f.write(jsonstr) | |
f.close() | |
# In[26]: | |
def myPredict(img_path, model): | |
img = image.load_img(img_path, target_size=(128, 128)) | |
x = image.img_to_array(img) | |
x = np.expand_dims(x, axis=0) | |
x = preprocess_input(x) | |
return model.predict(x)[0] | |
# In[27]: | |
preds = myPredict("test-tulips.jpg", model) | |
result = np.array(preds).argmax() | |
print(result) # ans: 4 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment