{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-08T08:00:53.457862Z","iopub.execute_input":"2024-02-08T08:00:53.458690Z","iopub.status.idle":"2024-02-08T08:00:53.811373Z","shell.execute_reply.started":"2024-02-08T08:00:53.458656Z","shell.execute_reply":"2024-02-08T08:00:53.810474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:00:57.973763Z","iopub.execute_input":"2024-02-08T08:00:57.974624Z","iopub.status.idle":"2024-02-08T08:01:14.408821Z","shell.execute_reply.started":"2024-02-08T08:00:57.974594Z","shell.execute_reply":"2024-02-08T08:01:14.407838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\ntrain_folder = 'train/'\n\n# define location of dataset\nfolder = train_folder\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:02:47.255391Z","iopub.execute_input":"2024-02-08T08:02:47.256568Z","iopub.status.idle":"2024-02-08T08:02:48.441800Z","shell.execute_reply.started":"2024-02-08T08:02:47.256533Z","shell.execute_reply":"2024-02-08T08:02:48.440921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:03:09.117328Z","iopub.execute_input":"2024-02-08T08:03:09.118048Z","iopub.status.idle":"2024-02-08T08:03:10.190001Z","shell.execute_reply.started":"2024-02-08T08:03:09.118003Z","shell.execute_reply":"2024-02-08T08:03:10.189125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder\n","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:03:31.254430Z","iopub.execute_input":"2024-02-08T08:03:31.255046Z","iopub.status.idle":"2024-02-08T08:03:31.260491Z","shell.execute_reply.started":"2024-02-08T08:03:31.255002Z","shell.execute_reply":"2024-02-08T08:03:31.259592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:03:59.300670Z","iopub.execute_input":"2024-02-08T08:03:59.301014Z","iopub.status.idle":"2024-02-08T08:04:18.288529Z","shell.execute_reply.started":"2024-02-08T08:03:59.300986Z","shell.execute_reply":"2024-02-08T08:04:18.287670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:04:18.289908Z","iopub.execute_input":"2024-02-08T08:04:18.290427Z","iopub.status.idle":"2024-02-08T08:04:18.295088Z","shell.execute_reply.started":"2024-02-08T08:04:18.290402Z","shell.execute_reply":"2024-02-08T08:04:18.294228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:05:35.949202Z","iopub.execute_input":"2024-02-08T08:05:35.949888Z","iopub.status.idle":"2024-02-08T08:05:35.954944Z","shell.execute_reply.started":"2024-02-08T08:05:35.949857Z","shell.execute_reply":"2024-02-08T08:05:35.954003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n#for file in listdir(folder[:10_000]): # select 10_000 images\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:05:50.932617Z","iopub.execute_input":"2024-02-08T08:05:50.933037Z","iopub.status.idle":"2024-02-08T08:07:17.541637Z","shell.execute_reply.started":"2024-02-08T08:05:50.933004Z","shell.execute_reply":"2024-02-08T08:07:17.540718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:08:32.272925Z","iopub.execute_input":"2024-02-08T08:08:32.273865Z","iopub.status.idle":"2024-02-08T08:08:33.603039Z","shell.execute_reply.started":"2024-02-08T08:08:32.273830Z","shell.execute_reply":"2024-02-08T08:08:33.602069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directories\nimport os\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tos.makedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:09:30.028131Z","iopub.execute_input":"2024-02-08T08:09:30.028548Z","iopub.status.idle":"2024-02-08T08:09:30.037348Z","shell.execute_reply.started":"2024-02-08T08:09:30.028516Z","shell.execute_reply":"2024-02-08T08:09:30.036302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:09:49.198210Z","iopub.execute_input":"2024-02-08T08:09:49.198652Z","iopub.status.idle":"2024-02-08T08:10:06.547240Z","shell.execute_reply.started":"2024-02-08T08:09:49.198619Z","shell.execute_reply":"2024-02-08T08:10:06.546296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l test1 | wc","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:11:23.044276Z","iopub.execute_input":"2024-02-08T08:11:23.044657Z","iopub.status.idle":"2024-02-08T08:11:24.409615Z","shell.execute_reply.started":"2024-02-08T08:11:23.044630Z","shell.execute_reply":"2024-02-08T08:11:24.408495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:11:32.412293Z","iopub.execute_input":"2024-02-08T08:11:32.413201Z","iopub.status.idle":"2024-02-08T08:11:33.684719Z","shell.execute_reply.started":"2024-02-08T08:11:32.413151Z","shell.execute_reply":"2024-02-08T08:11:33.683698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:11:39.114477Z","iopub.execute_input":"2024-02-08T08:11:39.115212Z","iopub.status.idle":"2024-02-08T08:11:40.394120Z","shell.execute_reply.started":"2024-02-08T08:11:39.115176Z","shell.execute_reply":"2024-02-08T08:11:40.392832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=1)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:16:05.907453Z","iopub.execute_input":"2024-02-08T08:16:05.908583Z","iopub.status.idle":"2024-02-08T08:16:05.922417Z","shell.execute_reply.started":"2024-02-08T08:16:05.908546Z","shell.execute_reply":"2024-02-08T08:16:05.921523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q\n","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:13:58.893292Z","iopub.execute_input":"2024-02-08T08:13:58.893721Z","iopub.status.idle":"2024-02-08T08:14:15.514922Z","shell.execute_reply.started":"2024-02-08T08:13:58.893687Z","shell.execute_reply":"2024-02-08T08:14:15.513861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:14:37.234930Z","iopub.execute_input":"2024-02-08T08:14:37.235923Z","iopub.status.idle":"2024-02-08T08:14:37.249927Z","shell.execute_reply.started":"2024-02-08T08:14:37.235886Z","shell.execute_reply":"2024-02-08T08:14:37.248993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.xception import Xception\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n    # Load Xception model, excluding top layers\n    model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n    # Freeze pre-trained layers\n    for layer in model.layers:\n        layer.trainable = False\n\n    # Add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n\n    # Define the new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # Compile the model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n\n    # create data generator\n    datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n    )\n\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(299, 299))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(299, 299))\n\n    # fit model\n    history = model.fit(train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=test_it,\n    validation_steps=len(test_it),\n    epochs=12,\n    verbose=1,\n    callbacks=[PlotLossesKeras()])\n\n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n\n    # learning curves\n    summarize_diagnostics(history)\n\n\n\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:21:46.281516Z","iopub.execute_input":"2024-02-08T08:21:46.281915Z","iopub.status.idle":"2024-02-08T10:00:43.567571Z","shell.execute_reply.started":"2024-02-08T08:21:46.281886Z","shell.execute_reply":"2024-02-08T10:00:43.566465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport sys\nfrom matplotlib import pyplot\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD\n\n\n# define cnn model\ndef define_model():\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:15]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    \n    opt = SGD(learning_rate=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n   # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    # fit model\n    history = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=10, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics(history)\n\n\nrun_test_harness()\n    \n    \n","metadata":{"execution":{"iopub.status.busy":"2024-02-08T13:01:52.563643Z","iopub.execute_input":"2024-02-08T13:01:52.564538Z","iopub.status.idle":"2024-02-08T13:49:56.373082Z","shell.execute_reply.started":"2024-02-08T13:01:52.564498Z","shell.execute_reply":"2024-02-08T13:49:56.372200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.applications import DenseNet201\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras\n\n# Define CNN model\ndef define_model():\n    # Load DenseNet201 model\n    model = DenseNet201(weights='imagenet', include_top=False, input_shape=(299, 299, 3))\n\n    # Mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\n    # Add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n\n    # Define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # Compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model\n\n# Plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # Plot loss and accuracy\n    plot_losses = PlotLossesKeras()\n    plot_losses.plot_history(history)\n    plot_losses.plot()\n\n# Run the test harness for evaluating a model\ndef run_test_harness():\n    # Define model\n    model = define_model()\n\n    # Create data generator with more aggressive data augmentation\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n\n    # Prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n                                           class_mode='binary', batch_size=64, target_size=(299, 299))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(299, 299))\n\n    # Fit model with live plotting\n    history = model.fit(train_it,\n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it,\n                        validation_steps=len(test_it),\n                        epochs=10,\n                        verbose=1,\n                        callbacks=[PlotLossesKeras()])\n\n    # Evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n\n    # Learning curves\n    summarize_diagnostics(history)\n\n# Run the test harness\nrun_test_harness()\n","metadata":{"execution":{"iopub.status.busy":"2024-02-08T14:59:23.088240Z","iopub.execute_input":"2024-02-08T14:59:23.089349Z","iopub.status.idle":"2024-02-08T16:22:37.671798Z","shell.execute_reply.started":"2024-02-08T14:59:23.089314Z","shell.execute_reply":"2024-02-08T16:22:37.670544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T16:31:14.624702Z","iopub.execute_input":"2024-02-08T16:31:14.625577Z","iopub.status.idle":"2024-02-08T16:31:20.831568Z","shell.execute_reply.started":"2024-02-08T16:31:14.625540Z","shell.execute_reply":"2024-02-08T16:31:20.830783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T16:31:27.683043Z","iopub.execute_input":"2024-02-08T16:31:27.683434Z","iopub.status.idle":"2024-02-08T16:31:29.482316Z","shell.execute_reply.started":"2024-02-08T16:31:27.683401Z","shell.execute_reply":"2024-02-08T16:31:29.481301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}