text_plain_output_2.png text_plain_output_1.png
from tensorflow.keras.applications.vgg16 import VGG16

from tensorflow.keras.backend import clear_session

from tensorflow.keras.layers import Convolution2D,MaxPooling2D, Dense, Flatten, InputLayer

from tensorflow.keras.models import Sequential, Model, load_model

from tensorflow.keras.optimizers import SGD

from tensorflow.keras.preprocessing.image import ImageDataGenerator

import pandas as pd

import zipfile

import zipfile
input_path = '/kaggle/input/dogs-vs-cats'
work_path = '/kaggle/working/data'
train_path = os.path.join(input_path, 'train.zip')
test_path = os.path.join(input_path, 'test1.zip')
with zipfile.ZipFile(train_path, 'r') as zip_ref:
    zip_ref.extractall(work_path)
with zipfile.ZipFile(test_path, 'r') as zip_ref:
    zip_ref.extractall(work_path)

data_dir = work_path
train_dir = data_dir + '/train'
test_dir = data_dir + '/test1'

df = pd.DataFrame()
fnames = os.listdir(train_dir)
class_name = []
for name in fnames:
    class_name.append(name.split('.')[0])
data = {'filename': fnames, 'class': class_name}
df = pd.DataFrame(data)
df = df.sample(frac=1)
train_datagen = ImageDataGenerator(rescale=1 / 255, rotation_range=20, shear_range=0.2, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True, zoom_range=0.2)
valid_datagen = ImageDataGenerator(rescale=1 / 255)
idx = int(0.8 * len(df))
train_df = df.iloc[:idx]
valid_df = df.iloc[idx:]
target = (224, 224)
train_set = train_datagen.flow_from_dataframe(train_df, directory=train_dir, shuffle=True, target_size=target, batch_size=64, class_mode='binary')
valid_set = valid_datagen.flow_from_dataframe(valid_df, directory=train_dir, shuffle=False, target_size=target, batch_size=32, class_mode='binary')

clear_session()
model = Sequential([InputLayer(input_shape=target + (3,)), Convolution2D(16, 3, activation='relu'), MaxPooling2D(2), Convolution2D(32, 3, activation='relu'), MaxPooling2D(2), Convolution2D(64, 3, activation='relu'), MaxPooling2D(2), Flatten(), Dense(512, activation='relu'), Dense(1, activation='sigmoid')])
model.summary()
opt = SGD(learning_rate=0.05, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc'])
model.optimizer.get_config()

clear_session()
model = VGG16(include_top=False, input_shape=target + (3,))
for layer in model.layers:
    layer.trainable = False
flat1 = Flatten()(model.layers[-1].output)
class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
output = Dense(1, activation='sigmoid')(class1)
model = Model(inputs=model.inputs, outputs=output)
model.summary()
opt = SGD(learning_rate=0.001, momentum=0.9)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc'])
model.optimizer.get_config()