{"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":"# 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":"2022-11-09T11:25:25.569840Z","iopub.execute_input":"2022-11-09T11:25:25.570495Z","iopub.status.idle":"2022-11-09T11:25:25.641689Z","shell.execute_reply.started":"2022-11-09T11:25:25.570448Z","shell.execute_reply":"2022-11-09T11:25:25.640307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Libraries to load\n\nimport os        \nimport numpy as np # linear algebra\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport PIL\nimport PIL.Image\nfrom tensorflow import keras\nimport tensorflow_datasets as tfds\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-11-10T09:51:37.492257Z","iopub.execute_input":"2022-11-10T09:51:37.492666Z","iopub.status.idle":"2022-11-10T09:51:45.509173Z","shell.execute_reply.started":"2022-11-10T09:51:37.492581Z","shell.execute_reply":"2022-11-10T09:51:45.507945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True","metadata":{"execution":{"iopub.status.busy":"2022-11-10T04:20:41.398537Z","iopub.execute_input":"2022-11-10T04:20:41.399293Z","iopub.status.idle":"2022-11-10T04:20:41.404656Z","shell.execute_reply.started":"2022-11-10T04:20:41.399244Z","shell.execute_reply":"2022-11-10T04:20:41.402782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Defines & compiles the model\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),\ntf.keras.layers.MaxPooling2D(2, 2),\nkeras.layers.Dropout(rate=0.15), #adding dropout regularization throughout the model to deal with overfitting\n# The second convolution\ntf.keras.layers.Conv2D(32, (3,3), activation='relu'),\ntf.keras.layers.MaxPooling2D(2,2),\nkeras.layers.Dropout(rate=0.1),\n# The third convolution\ntf.keras.layers.Conv2D(64, (3,3), activation='relu'),\ntf.keras.layers.MaxPooling2D(2,2),\nkeras.layers.Dropout(rate=0.10),\n# Flatten the results to feed into a DNN\ntf.keras.layers.Flatten(),\n# 512 neuron hidden layer\ntf.keras.layers.Dense(512, activation='relu'),\n\n# 3 output neuron for the 3 classes of Animal Images\ntf.keras.layers.Dense(6, activation='softmax')\n])\n\nfrom tensorflow.keras.optimizers import RMSprop\n\nmodel.compile(loss='categorical_crossentropy',\n          optimizer=\"adam\",\n          metrics=['acc'])\n\n\n# Creates an instance of an ImageDataGenerator called train_datagen, and a train_generator, train_datagen.flow_from_directory\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n#splits data into training and testing(validation) sets\ntrain_datagen =ImageDataGenerator(rescale=1./255, validation_split=0.25)\n\nimport matplotlib.pyplot as plt\n\n\n#training data\ntrain_generator = train_datagen.flow_from_directory(\n    '../input/finding-disney/train',  # Source directory\n    target_size=(150, 150),  # Resizes images\n    batch_size=15,\n    class_mode='categorical',subset = 'training')\n\n\nepochs = 15\n#Testing data\nvalidation_generator = train_datagen.flow_from_directory(\n'../input/finding-disney/train',\ntarget_size=(150, 150),\nbatch_size=15,\nclass_mode='categorical',\nsubset='validation') # set as validation data\n\n#Model fitting for a number of epochs\nhistory = model.fit_generator(\n  train_generator,\n  steps_per_epoch=150,\n  epochs=epochs,\n  validation_data = validation_generator,\n  validation_steps = 50,\n  verbose=1)\n\n\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\n#This code is used to plot the training and validation accuracy\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\n# returns accuracy of training\nprint(\"Training Accuracy:\"), print(history.history['acc'][-1])\nprint(\"Testing Accuracy:\"), print (history.history['val_acc'][-1])","metadata":{"execution":{"iopub.status.busy":"2022-11-10T04:20:44.009991Z","iopub.execute_input":"2022-11-10T04:20:44.010317Z","iopub.status.idle":"2022-11-10T04:37:11.960478Z","shell.execute_reply.started":"2022-11-10T04:20:44.010292Z","shell.execute_reply":"2022-11-10T04:37:11.959073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator.class_indices\ntrain_generator.samples","metadata":{"execution":{"iopub.status.busy":"2022-11-10T04:44:29.708946Z","iopub.execute_input":"2022-11-10T04:44:29.709341Z","iopub.status.idle":"2022-11-10T04:44:29.717323Z","shell.execute_reply.started":"2022-11-10T04:44:29.709315Z","shell.execute_reply":"2022-11-10T04:44:29.716247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nimg = Image.open('../input/finding-disney/test/10182.jpg')\nimg","metadata":{"execution":{"iopub.status.busy":"2022-11-10T09:52:50.493088Z","iopub.execute_input":"2022-11-10T09:52:50.493441Z","iopub.status.idle":"2022-11-10T09:52:50.654001Z","shell.execute_reply.started":"2022-11-10T09:52:50.493413Z","shell.execute_reply":"2022-11-10T09:52:50.653175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dir = '../input/finding-disney/test'\nl_id = []\nfor file in os.listdir(test_dir):\n    l_id.append(file.split('.')[0])\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T10:04:36.499213Z","iopub.execute_input":"2022-11-10T10:04:36.499564Z","iopub.status.idle":"2022-11-10T10:04:36.505758Z","shell.execute_reply.started":"2022-11-10T10:04:36.499537Z","shell.execute_reply":"2022-11-10T10:04:36.504533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# character_id = pd.DataFrame(l_id)\n# submission = character_id\n# submission\n\nsubmission = pd.DataFrame(columns=['character_id'])\nsubmission['character_id'] = pd.DataFrame(l_id)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2022-11-10T10:23:36.032794Z","iopub.execute_input":"2022-11-10T10:23:36.033661Z","iopub.status.idle":"2022-11-10T10:23:36.049461Z","shell.execute_reply.started":"2022-11-10T10:23:36.033623Z","shell.execute_reply":"2022-11-10T10:23:36.047504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}