{"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        break\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":"2023-06-30T02:14:38.836075Z","iopub.execute_input":"2023-06-30T02:14:38.836444Z","iopub.status.idle":"2023-06-30T02:14:46.443856Z","shell.execute_reply.started":"2023-06-30T02:14:38.836414Z","shell.execute_reply":"2023-06-30T02:14:46.442815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport os\nimport shutil\nfrom PIL import Image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import image_dataset_from_directory\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import models\nfrom tensorflow.keras.applications import InceptionV3","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:14:49.580867Z","iopub.execute_input":"2023-06-30T02:14:49.581228Z","iopub.status.idle":"2023-06-30T02:14:52.652870Z","shell.execute_reply.started":"2023-06-30T02:14:49.581200Z","shell.execute_reply":"2023-06-30T02:14:52.651963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = np.asarray(Image.open('/kaggle/input/dog-breed-identification/train/7d9c53fa846ea7e34bc3efa6830ab668.jpg'))\nimgplot = plt.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:14:57.539176Z","iopub.execute_input":"2023-06-30T02:14:57.539904Z","iopub.status.idle":"2023-06-30T02:14:57.968316Z","shell.execute_reply.started":"2023-06-30T02:14:57.539871Z","shell.execute_reply":"2023-06-30T02:14:57.967509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Diretórios e arquivos\ntrain_images_path='/kaggle/input/dog-breed-identification/train/'\ntest_images_path='/kaggle/input/dog-breed-identification/test'\nlabels_path_file='/kaggle/input/dog-breed-identification/labels.csv'","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:15:05.677858Z","iopub.execute_input":"2023-06-30T02:15:05.678240Z","iopub.status.idle":"2023-06-30T02:15:05.683548Z","shell.execute_reply.started":"2023-06-30T02:15:05.678212Z","shell.execute_reply":"2023-06-30T02:15:05.682402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Criando diretório para separar as imagens pelas raças dos cães\ndef make_dir(x):\n    if os.path.exists(x)==False:\n        os.makedirs(x)\n        \nbase_dir = './subset'\nmake_dir(base_dir)\ntrain_dir = os.path.join(base_dir, 'train')\nmake_dir(train_dir)","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:15:47.458010Z","iopub.execute_input":"2023-06-30T02:15:47.458392Z","iopub.status.idle":"2023-06-30T02:15:47.465378Z","shell.execute_reply.started":"2023-06-30T02:15:47.458363Z","shell.execute_reply":"2023-06-30T02:15:47.464219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_csv(labels_path_file)\nnum_classes = len(labels.breed.unique())\nprint(f\"Quantidade raças: {num_classes}\")","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:15:52.657859Z","iopub.execute_input":"2023-06-30T02:15:52.658231Z","iopub.status.idle":"2023-06-30T02:15:52.679737Z","shell.execute_reply.started":"2023-06-30T02:15:52.658201Z","shell.execute_reply":"2023-06-30T02:15:52.678753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Copiando as imagens para o diretório da raça\nbreeds = labels.breed.unique()\nfor breed in breeds:\n    # Make folder for each breed\n    _ = os.path.join(train_dir, breed)\n    make_dir(_)\n    \n    # Copy images to the corresponding folders\n    images = labels[labels.breed == breed]['id']\n    for image in images:\n        source = os.path.join(train_images_path, f'{image}.jpg')\n        destination = os.path.join(train_dir, breed,f'{image}.jpg')                             \n        shutil.copyfile(source, destination)","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:15:56.759904Z","iopub.execute_input":"2023-06-30T02:15:56.760264Z","iopub.status.idle":"2023-06-30T02:16:09.263241Z","shell.execute_reply.started":"2023-06-30T02:15:56.760236Z","shell.execute_reply":"2023-06-30T02:16:09.262139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reduzir o uso da memória\ndatagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = datagen.flow_from_directory(\n    directory=train_dir,\n    target_size=(224, 224),\n    batch_size=128,\n    class_mode='sparse')","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:16:17.300399Z","iopub.execute_input":"2023-06-30T02:16:17.300755Z","iopub.status.idle":"2023-06-30T02:16:17.907100Z","shell.execute_reply.started":"2023-06-30T02:16:17.300725Z","shell.execute_reply":"2023-06-30T02:16:17.906169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"InceptionV3_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nInceptionV3_model.trainable = False\n\nmodel = models.Sequential()\nmodel.add(InceptionV3_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(layers.Dropout(0.2))\nmodel.add(layers.Dense(num_classes, activation='softmax'))\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:16:30.780343Z","iopub.execute_input":"2023-06-30T02:16:30.780712Z","iopub.status.idle":"2023-06-30T02:16:37.467546Z","shell.execute_reply.started":"2023-06-30T02:16:30.780680Z","shell.execute_reply":"2023-06-30T02:16:37.466506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10)\n\nhistory = model.fit(train_generator, \n          batch_size=128, \n          epochs=20,\n          verbose=1, \n          callbacks=[early_stop],\n          shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-30T02:17:04.101235Z","iopub.execute_input":"2023-06-30T02:17:04.101825Z","iopub.status.idle":"2023-06-30T02:30:07.419509Z","shell.execute_reply.started":"2023-06-30T02:17:04.101756Z","shell.execute_reply":"2023-06-30T02:30:07.418467Z"},"trusted":true},"execution_count":null,"outputs":[]}]}