text_plain_output_1.png
from os import listdir

from os.path import isfile, join

from tensorflow.keras.callbacks import EarlyStopping

from tensorflow.keras.callbacks import ModelCheckpoint

from tensorflow.keras.layers import Conv2D

from tensorflow.keras.layers import Dense

from tensorflow.keras.layers import Flatten

from tensorflow.keras.layers import MaxPooling2D

from tensorflow.keras.models import Sequential

from tensorflow.keras.models import load_model

from tensorflow.keras.optimizers import SGD

from tensorflow.keras.preprocessing import image

from tensorflow.keras.preprocessing.image import ImageDataGenerator

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import random

K.clear_session()

img_width = img_height = 224
training_data_dir = '../input/my-dogs-vs-cats/my-dogs-vs-cats/training'
validation_data_dir = '../input/my-dogs-vs-cats/my-dogs-vs-cats/validation'
batch_size = 32

train_datagen = ImageDataGenerator(rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)

train_generator = train_datagen.flow_from_directory(training_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')

valid_datagen = ImageDataGenerator(rescale=1.0 / 255)

validation_generator = valid_datagen.flow_from_directory(validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary')

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

def VGG16():
    model = Sequential()
    model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', input_shape=input_shape, activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(Conv2D(filters=128, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=128, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(Conv2D(filters=256, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=256, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=256, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(Conv2D(filters=512, kernel_size=(3, 3), padding='same', activation='relu', kernel_initializer='he_uniform'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(Flatten(name='flatten'))
    model.add(Dense(4096, activation='relu', name='fc1'))
    model.add(Dense(4096, activation='relu', name='fc2'))
    model.add(Dense(1, activation='sigmoid', name='output'))
    return model

model = VGG16()

early_stopping = EarlyStopping(monitor='val_accuracy', mode='auto', verbose=1, patience=3)

model_checkpoint = ModelCheckpoint(filepath='./checkpoint.h5', monitor='val_accuracy', save_best_only=True, mode='auto')
callbacks = [early_stopping, model_checkpoint]

opt = SGD(learning_rate=0.001, momentum=0.9)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])

model.summary()

epochs = 2
steps_per_epoch = len(train_generator)
validation_steps = len(validation_generator)

history = model.fit_generator(generator=train_generator, validation_data=validation_generator, epochs=epochs, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, callbacks=callbacks, verbose=1)

model = load_model('../input/modelcheckpoint/final_model.h5')

import matplotlib.pyplot as plt
import random
import pandas as pd
from tensorflow.keras.preprocessing import image
df = pd.read_csv('../input/my-dogs-vs-cats/my-dogs-vs-cats/sampleSubmission.csv')
def updateValue(df: pd.DataFrame, id: int, value: str):
    df.loc[df['id'] == id, 'label'] = value
predict_dir_path = '../input/my-dogs-vs-cats/my-dogs-vs-cats/test'
onlyfiles = [f for f in listdir(predict_dir_path) if isfile(join(predict_dir_path, f))]
random.shuffle(onlyfiles)
dog_counter = 0
cat_counter = 0
counter = 0
times = 100
for file, counter in zip(onlyfiles, range(times)):
    img = image.load_img(predict_dir_path + '/' + file, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    images = np.vstack([x])
    classes = model.predict(images, batch_size=10)
    classes = classes[0][0]
    id = str(file).split('.')
    id = int(id[0])
    if classes == 0:
        updateValue(df, id, 'cat')
        cat_counter += 1
    else:
        updateValue(df, id, 'dog')
        dog_counter += 1
df.to_csv('./sampleSubmission.csv', index=False)

df = pd.read_csv('./sampleSubmission.csv')
print(df.loc[df['label'] == 'dog'].to_string(index=False))
print('-------------------------')
print(df.loc[df['label'] == 'cat'].to_string(index=False))