Skip to content

Instantly share code, notes, and snippets.

@tbmreza
Created February 26, 2019 14:34
Show Gist options
  • Save tbmreza/daf2ffe519e1a8eb4979636dcbc02aa7 to your computer and use it in GitHub Desktop.
Save tbmreza/daf2ffe519e1a8eb4979636dcbc02aa7 to your computer and use it in GitHub Desktop.
from keras.applications import densenet
from keras.preprocessing import image
from keras.applications.densenet import preprocess_input, decode_predictions
import numpy as np
from keras.layers import Dense, GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam
import os
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory('pisang-train/',
target_size=(224,224),
color_mode='rgb',
batch_size=32,
class_mode='categorical',
shuffle=True)
category_dict = train_generator.class_indices
print(category_dict)
number_of_classes = len(category_dict)
base_model = densenet.DenseNet121(weights='densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5',
include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(512, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x)
preds = Dense(number_of_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=preds)
# Print the updated layer names.
# for i,layer in enumerate(model.layers): print(i,layer.name)
# Set the first n_freeze layers of the network to be non-trainable.
n_freeze = 300
for layer in model.layers[:n_freeze]:
layer.trainable=False
for layer in model.layers[n_freeze:]:
layer.trainable=True
model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])
step_size_train = train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
steps_per_epoch=step_size_train,
epochs=10)
# Without transfer learning.
default_model = densenet.DenseNet121(weights='densenet121_weights_tf_dim_ordering_tf_kernels.h5')
test_path = 'pisang-test/'
for directory in os.listdir(test_path):
# Load image.
img_path = test_path+directory
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
default_preds = default_model.predict(x)
# Printing results.
# Default 1000 classes (without transfer learning).
print(f"Without Transfer Learning Top-2 [{directory}]: \n{decode_predictions(default_preds, top=2)[0]}\n")
# Print transfer learning model top-1
confidence_array = preds[0]
index_max = np.argmax(confidence_array)
# Get KEY (category) by VALUE (index_max) in dictionary
# mydict = {'george':16,'amber':19}
# print(list(mydict.keys())[list(mydict.values()).index(16)]) # Example in one line.
category_names = category_dict.keys()
category_values = category_dict.values()
category_at_index = list(category_values).index(index_max)
category_max = list(category_names)[category_at_index]
print(f"\nWith Transfer Learning [{directory}]: \nTop-1 (confidence)\n{category_max} ({max(confidence_array)*100}%)")
# Print transfer learning model all classes
print("\nClass (confidence)")
for category in category_dict:
category_index = category_dict[category]
value = confidence_array[category_index] * 100
print(f"{category} ({value}%)")
print("\n============================\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment