{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from zipfile import ZipFile as zf\ntrain_zip = zf('/kaggle/input/dogs-vs-cats/train.zip', 'r')\ntrain_zip.extractall()\ntrain_zip.close()\ntest_zip = zf('/kaggle/input/dogs-vs-cats/test1.zip', 'r')\ntest_zip.extractall()\ntest_zip.close()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-09-04T12:55:26.979345Z","iopub.execute_input":"2021-09-04T12:55:26.979656Z","iopub.status.idle":"2021-09-04T12:55:39.701694Z","shell.execute_reply.started":"2021-09-04T12:55:26.979629Z","shell.execute_reply":"2021-09-04T12:55:39.700880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from os import makedirs\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)","metadata":{"execution":{"iopub.status.busy":"2021-09-04T13:03:31.571312Z","iopub.execute_input":"2021-09-04T13:03:31.571644Z","iopub.status.idle":"2021-09-04T13:03:31.577211Z","shell.execute_reply.started":"2021-09-04T13:03:31.571613Z","shell.execute_reply":"2021-09-04T13:03:31.576390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from os import listdir\nfrom numpy import save\nfrom random import seed\nfrom random import random\nfrom shutil import copyfile\n\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":"2021-09-04T13:06:35.563965Z","iopub.execute_input":"2021-09-04T13:06:35.564299Z","iopub.status.idle":"2021-09-04T13:06:39.377485Z","shell.execute_reply.started":"2021-09-04T13:06:35.564269Z","shell.execute_reply":"2021-09-04T13:06:39.376509Z"},"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 tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import concatenate\nfrom keras.applications.vgg19 import VGG19\n\n# define VGG model\ndef VGG():\n\t# load model\n\tmodel = VGG19(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\tdropout = Dropout(0.5)(class1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = Adam(learning_rate=0.001)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2021-09-04T13:06:49.617217Z","iopub.execute_input":"2021-09-04T13:06:49.617566Z","iopub.status.idle":"2021-09-04T13:06:53.969029Z","shell.execute_reply.started":"2021-09-04T13:06:49.617532Z","shell.execute_reply":"2021-09-04T13:06:53.968041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import CSVLogger\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# run the test harness for evaluating a model\ndef run_test_harness_vgg():\n  # define model\n\tmodel = VGG()\n\t# create data generator\n\tdatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\t# fit model\n\tcsv_logger = CSVLogger('training.log', separator=',', append=False)\n\thistory = model.fit(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=12, verbose=1, callbacks=[csv_logger])\n\t# evaluate model\n\t_, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\tmodel.save('final_model_vgg_1.h5')\n# entry point, run the test harness\nrun_test_harness_vgg()","metadata":{"execution":{"iopub.status.busy":"2021-09-04T13:08:47.853790Z","iopub.execute_input":"2021-09-04T13:08:47.854145Z","iopub.status.idle":"2021-09-04T13:34:47.543652Z","shell.execute_reply.started":"2021-09-04T13:08:47.854112Z","shell.execute_reply":"2021-09-04T13:34:47.542676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom keras.preprocessing.image import load_img\nfrom matplotlib import pyplot\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import array_to_img\nfrom keras.models import load_model\nimg_file = './test1/10043.jpg'\ndef load_image(filename):\n    # load the image\n    img = load_img(filename, target_size=(224, 224))\n    # convert to array\n    img = img_to_array(img)\n    # reshape into a single sample with 3 channels\n    img = img.reshape(1, 224, 224, 3)\n    # center pixel data\n    img = img.astype('float32')\n    img = img - [123.68, 116.779, 103.939]\n    return img\n\ndef predict(img_file):\n\t# load the image\n    img = load_image(img_file)\n\t# load model    \n    model = load_model('./final_model_vgg_1.h5')\n\t# predict the class    \n    result = model.predict(img)\n    classes = ['Cat', 'Dog']\n    print(classes[int(result[0][0])])\npredict(img_file)\nimg_test = load_img(img_file, target_size=(224, 224))\narr_ = np.squeeze(img_test)\npyplot.imshow(arr_)\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-04T13:54:32.886174Z","iopub.execute_input":"2021-09-04T13:54:32.886522Z","iopub.status.idle":"2021-09-04T13:54:33.499453Z","shell.execute_reply.started":"2021-09-04T13:54:32.886488Z","shell.execute_reply":"2021-09-04T13:54:33.498497Z"},"trusted":true},"execution_count":null,"outputs":[]}]}