{"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":"# Basic imports \nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2 as cv \nimport os\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2023-06-09T19:20:46.934164Z","iopub.execute_input":"2023-06-09T19:20:46.936594Z","iopub.status.idle":"2023-06-09T19:20:46.941707Z","shell.execute_reply.started":"2023-06-09T19:20:46.936553Z","shell.execute_reply":"2023-06-09T19:20:46.940591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        break","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-09T19:20:49.897510Z","iopub.execute_input":"2023-06-09T19:20:49.898637Z","iopub.status.idle":"2023-06-09T19:21:13.167443Z","shell.execute_reply.started":"2023-06-09T19:20:49.898582Z","shell.execute_reply":"2023-06-09T19:21:13.166309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Carrega o arquivo CSV chamado \"labels.csv\" contendo os rótulos de identificação das raças de cães e armazenar os dados na variável `labels`. Em seguida, a segunda coluna do array `labels` é extraída e atribuída à variável `y_train`.","metadata":{}},{"cell_type":"code","source":"labels = np.loadtxt(\"/kaggle/input/dog-breed-identification/labels.csv\", delimiter=\",\", dtype=str, skiprows=1)\nprint(labels[0:5])\ny_train = labels[:,1]\nprint()\nprint(y_train[0:5])","metadata":{"execution":{"iopub.status.busy":"2023-06-09T19:21:59.094042Z","iopub.execute_input":"2023-06-09T19:21:59.094439Z","iopub.status.idle":"2023-06-09T19:21:59.121582Z","shell.execute_reply.started":"2023-06-09T19:21:59.094404Z","shell.execute_reply":"2023-06-09T19:21:59.119941Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images_path='/kaggle/input/dog-breed-identification/train/'\ntest_images_path='/kaggle/input/dog-breed-identification/test/'\ntrain_files = [train_images_path + file_name + '.jpg' for file_name in labels[:,0]]\n\nunique_values = np.unique(labels[:, 1])\n\nprint(len(train_files), len(unique_values), train_files[:5])\n","metadata":{"execution":{"iopub.status.busy":"2023-06-09T19:23:50.614614Z","iopub.execute_input":"2023-06-09T19:23:50.615087Z","iopub.status.idle":"2023-06-09T19:23:50.632255Z","shell.execute_reply.started":"2023-06-09T19:23:50.615053Z","shell.execute_reply":"2023-06-09T19:23:50.630968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tam = 224\n\ndef img2arr(image_path):\n    img = tf.keras.utils.load_img(image_path,target_size=(tam,tam))\n    arr = tf.keras.utils.img_to_array(img)/255\n    return arr\n\nprint(img2arr(train_files[0]).shape)\nimgplot = plt.imshow(img2arr(train_files[0]))","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:06:05.036207Z","iopub.execute_input":"2023-06-09T20:06:05.036612Z","iopub.status.idle":"2023-06-09T20:06:05.359052Z","shell.execute_reply.started":"2023-06-09T20:06:05.036584Z","shell.execute_reply":"2023-06-09T20:06:05.357999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_size=-1\nx_train = np.empty((len(train_files[:train_size]),tam,tam,3))\n\nfor i, file in enumerate(train_files[:train_size]):\n    x_train[i] = img2arr(file)\n    \nprint(x_train.shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:06:13.066948Z","iopub.execute_input":"2023-06-09T20:06:13.067312Z","iopub.status.idle":"2023-06-09T20:06:37.601293Z","shell.execute_reply.started":"2023-06-09T20:06:13.067285Z","shell.execute_reply":"2023-06-09T20:06:37.600134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"A função `img2arr(image_path)` recebe o caminho de uma imagem como entrada e realiza as seguintes operações:\n\nA função `tf.keras.utils.load_img()` é usada para carregar a imagem do caminho especificado. O parâmetro target_size é fornecido para redimensionar a imagem para o tamanho especificado (tam, tam).\nA função `tf.keras.utils.img_to_array()` é usada para converter a imagem em um array de NumPy. Isso significa que a imagem é transformada em uma matriz tridimensional, onde cada elemento da matriz representa um pixel da imagem.\nA `divisão por 255` é realizada para **normalizar** os valores dos pixels no intervalo de 0 a 1. Dividir por 255 é comum para normalizar as intensidades dos pixels em imagens, onde 255 é o valor máximo possível para um pixel em uma imagem de 8 bits.\nA função retorna o array resultante.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom tensorflow.keras import layers\nfrom sklearn.metrics import accuracy_score","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:07:38.106279Z","iopub.execute_input":"2023-06-09T20:07:38.107707Z","iopub.status.idle":"2023-06-09T20:07:38.817483Z","shell.execute_reply.started":"2023-06-09T20:07:38.107666Z","shell.execute_reply":"2023-06-09T20:07:38.816417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tam = 100\n\ndef img2arr(image_path):\n    img = tf.keras.utils.load_img(image_path,target_size=(tam,tam))\n    arr = tf.keras.utils.img_to_array(img)/255\n    return arr\n\nprint(img2arr(train_files[0]).shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:07:41.235009Z","iopub.execute_input":"2023-06-09T20:07:41.235745Z","iopub.status.idle":"2023-06-09T20:07:41.246275Z","shell.execute_reply.started":"2023-06-09T20:07:41.235711Z","shell.execute_reply":"2023-06-09T20:07:41.245537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_size=-1\nx_train = np.empty((len(train_files[:train_size]),tam,tam,3))\n\nfor i, file in enumerate(train_files[:train_size]):\n    x_train[i] = img2arr(file)\n\nprint(x_train.shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:07:43.271330Z","iopub.execute_input":"2023-06-09T20:07:43.271724Z","iopub.status.idle":"2023-06-09T20:08:03.310878Z","shell.execute_reply.started":"2023-06-09T20:07:43.271690Z","shell.execute_reply":"2023-06-09T20:08:03.309785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class RedeNeural(BaseEstimator, ClassifierMixin):\n  def __init__(self, epochs=5, batch_size=32):\n    self.epochs = epochs\n    self.batch_size = batch_size\n\n  def fit(self, X, y):\n    self.labels, ids = np.unique(y, return_inverse=True)\n    yhot = keras.utils.to_categorical(ids)\n    self.model = keras.Sequential([\n        layers.Conv2D(4, 4, activation='relu'),\n        layers.Flatten(),\n        layers.Dense(512, activation=\"relu\"),\n        layers.Dense(yhot.shape[1], activation=\"softmax\")\n    ])\n    self.model.compile(optimizer=\"rmsprop\",\n                       loss=\"categorical_crossentropy\",\n                       metrics=[\"accuracy\"])\n    self.model.fit(X, yhot, epochs=self.epochs, batch_size=self.batch_size)\n    return self\n\n  def predict(self, X, y=None):\n    return self.model.predict(X)\n\nmodelo = RedeNeural()\nmodelo.fit(x_train, y_train[:train_size])\nmodelo.model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:08:03.312493Z","iopub.execute_input":"2023-06-09T20:08:03.312799Z","iopub.status.idle":"2023-06-09T20:14:02.245969Z","shell.execute_reply.started":"2023-06-09T20:08:03.312773Z","shell.execute_reply":"2023-06-09T20:14:02.244927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_files = []\n\nfor dirname, _, filenames in os.walk('/kaggle/input/dog-breed-identification/test/'):\n    for filename in filenames:\n        test_files.append(os.path.join(dirname, filename))\n\nprint(len(test_files))","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:15:25.503349Z","iopub.execute_input":"2023-06-09T20:15:25.504491Z","iopub.status.idle":"2023-06-09T20:15:27.401998Z","shell.execute_reply.started":"2023-06-09T20:15:25.504454Z","shell.execute_reply":"2023-06-09T20:15:27.400828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test = np.empty((len(test_files),tam,tam,3))\n\nfor i, file in enumerate(test_files):\n    x_test[i] = img2arr(file)\n\nprint(x_test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:15:36.242966Z","iopub.execute_input":"2023-06-09T20:15:36.243394Z","iopub.status.idle":"2023-06-09T20:16:36.195999Z","shell.execute_reply.started":"2023-06-09T20:15:36.243361Z","shell.execute_reply":"2023-06-09T20:16:36.194940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = modelo.predict(x_test)\n\nnp.savetxt(\"submission.csv\", y_pred, delimiter=\",\")\n\nprint(y_pred[:10])","metadata":{"execution":{"iopub.status.busy":"2023-06-09T20:17:29.950652Z","iopub.execute_input":"2023-06-09T20:17:29.951098Z","iopub.status.idle":"2023-06-09T20:17:53.453853Z","shell.execute_reply.started":"2023-06-09T20:17:29.951064Z","shell.execute_reply":"2023-06-09T20:17:53.452369Z"},"trusted":true},"execution_count":null,"outputs":[]}]}