{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Imports"},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport json\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sn\nimport matplotlib.pyplot as plt\nimport cv2\nimport albumentations as A\nfrom sklearn import metrics as sk_metrics\nfrom skimage.io import imread\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Nombres Directorios"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"BASE_DIR = \"../input/cassava-leaf-disease-classification/\"\nTRAIN_PATH = BASE_DIR + \"train_images/\"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Direccion"},{"metadata":{"trusted":true},"cell_type":"code","source":"with open(os.path.join(BASE_DIR, \"label_num_to_disease_map.json\")) as file:\n    map_classes = json.loads(file.read())\n    map_classes = {int(k) : v for k, v in map_classes.items()}\n    \nprint(json.dumps(map_classes, indent=4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_files = os.listdir(os.path.join(BASE_DIR, \"train_images\"))\nprint(f\"Number of train images: {len(input_files)}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datos = pd.read_csv(BASE_DIR+\"train.csv\")\ndatos","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datos.groupby('label')['image_id'].count()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Cargar las fotos"},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_WIDTH = IMAGE_HEIGHT = 64\ndef cargar_fotos(directorio):\n    X = []\n    Y = []\n    for image in os.listdir(directorio):\n        foto = imread(directorio+image)\n        smallimage = cv2.resize(foto, (IMAGE_WIDTH, IMAGE_HEIGHT)) \n        X.append(smallimage) \n        category = datos[datos[\"image_id\"] == image]['label'].values[0]\n        Y.append(category)\n\n    return np.array(X), np.array(Y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, y_train = cargar_fotos(TRAIN_PATH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X_train[0]);","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Estandarizar"},{"metadata":{"trusted":true},"cell_type":"code","source":"# solo ejecutar una vez\nprint(\"Min:\", np.min(X_train))\nprint(\"Max:\", np.max(X_train))\n\nX_train = X_train / 255.0\n\nprint(\"Min:\", np.min(X_train))\nprint(\"Max:\", np.max(X_train))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Shuffle"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.utils import shuffle \n\nX_train, y_train = shuffle(X_train, y_train, random_state = 42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Separar datos en train y test"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X_train\ny = y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Modelos"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([\n    tf.keras.layers.Conv2D(32, (3,3),   \n                        activation = 'relu',\n                       input_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, 3)),  \n    \n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(64, (3,3),\n                       activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(128, activation = 'relu'),\n    tf.keras.layers.Dense(5, activation = 'softmax') \n    \n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = 'adam',      # que funcion de coste minimizar\n             loss = 'sparse_categorical_crossentropy', #sparse_categorical_crossentrophy si tuvieramos mas\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping\nearlystop = EarlyStopping(patience=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train,\n                   y_train,\n                   epochs = 5,\n                    callbacks = [earlystop],\n                   validation_split = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.evaluate(X_test, y_test)\nprint(\"test loss, test acc:\", results)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}