Skip to content

Instantly share code, notes, and snippets.

@gtindo
Created December 3, 2019 23:32
Show Gist options
  • Save gtindo/f621db0ef932844c1b66e850d19547cb to your computer and use it in GitHub Desktop.
Save gtindo/f621db0ef932844c1b66e850d19547cb to your computer and use it in GitHub Desktop.
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import os
data = {
"filenames": [],
"categories": [],
}
DATA_PATH = 'data'
# Load Data
for file_name in os.listdir(DATA_PATH):
if os.path.isfile(file_name):
data["files"].append(file_name)
data["labels"].append(file_name.split(".")[0])
df = pd.DataFrame(data)
# Normalize image
datagen = ImageDataGenerator(rescale=1./255)
# Split data with train and test set
train_df, test_df = train_test_split(df, test_size=0.2)
# make train and valid generator
train_generator = datagen.flow_from_dataframe(
train_df, DATA_PATH,
x_col='filenames',
y_col='categories',
target_size=(224, 224),
class_mode='categorical',
batch_size=32
)
test_generator = datagen.flow_from_dataframe(
test_df, DATA_PATH,
x_col='categories',
y_col='categories',
target_size=(224, 224),
class_mode='categorical',
batch_size=32
)
# Build Model
model = Sequential()
model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(256, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(256, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
history = model.fit_generator(
train_generator,
epochs=20,
validation_data=test_generator,
validation_steps=len(test_generator),
steps_per_epoch=len(train_generator)
)
# Loss Plot
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# Accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_loss'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment