{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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":{"trusted":true},"cell_type":"code","source":"!df -h","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '/kaggle/input/cassava-leaf-disease-classification/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cat '/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!head -5 '/kaggle/input/cassava-leaf-disease-classification/train.csv'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '/kaggle/input/cassava-leaf-disease-classification/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv', sep = ',')\nprint(labels['label'].unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels['label'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels['image_id'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '/kaggle/input/cassava-leaf-disease-classification/test_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from IPython.display import Image\n\ndisplay(Image('/kaggle/input/cassava-leaf-disease-classification/test_images/2216849948.jpg', width=400, height=400))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '/kaggle/input/cassava-leaf-disease-classification/train_images/' | head -5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(Image('/kaggle/input/cassava-leaf-disease-classification/train_images/1000015157.jpg', width=400, height=400))\ndisplay(Image('/kaggle/input/cassava-leaf-disease-classification/train_images/1000201771.jpg', width=400, height=400))\ndisplay(Image('/kaggle/input/cassava-leaf-disease-classification/train_images/100042118.jpg', width=400, height=400))\ndisplay(Image('/kaggle/input/cassava-leaf-disease-classification/train_images/1000723321.jpg', width=400, height=400))\ndisplay(Image('/kaggle/input/cassava-leaf-disease-classification/train_images/1000812911.jpg', width=400, height=400))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%ls -l '/kaggle/input/cassava-leaf-disease-classification/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '/kaggle/input/cassava-leaf-disease-classification/train_images/' | wc -l","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd '/kaggle/working/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir 'train'\n%cd 'train'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir '0'\n!mkdir '1'\n!mkdir '2'\n!mkdir '3'\n!mkdir '4'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil\n\n\nfor i in range(0,len(labels),1):\n  file_name = str(labels.iloc[i]['image_id'])\n  target_folder = str(labels.iloc[i]['label'])\n  shutil.copyfile('/kaggle/input/cassava-leaf-disease-classification/train_images/'+file_name, target_folder+'/'+file_name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '0' | wc -l","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '1' | wc -l","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '2' | wc -l","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '3' | wc -l","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"imagenes de train y test estan en la carpeta train, por lo tanto usar imagedatagen para separar esto, y ya que esta desbalanceado usar class_weight en fit_from_generator (si es q aguanta) https://stackoverflow.com/questions/44666910/keras-image-preprocessing-unbalanced-data/44667582\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\ntf.__version__","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\ndatagen = ImageDataGenerator(rescale=1./255,\n                             brightness_range=[0.7,1.0],\n                             horizontal_flip=True,\n                             rotation_range=90,\n                             fill_mode='nearest',\n                             validation_split=0.2\n                            )\n\ntrain_generator = datagen.flow_from_directory('/kaggle/working/train/',\n                                              target_size=(100,100),\n                                              shuffle = True,\n                                              class_mode='categorical',\n                                              color_mode='rgb',\n                                              subset = 'training',\n                                              batch_size = 16\n                                             )\n\nval_generator = datagen.flow_from_directory('/kaggle/working/train/',\n                                            target_size=(100,100),\n                                            shuffle = True,\n                                            class_mode='categorical',\n                                            color_mode='rgb',\n                                            subset = 'validation',\n                                            batch_size = 16                                            \n                                           )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    \n    tf.keras.layers.Conv2D(input_shape = (100,100,3),  filters = 128, kernel_size = (4,4), strides=(1, 1), padding='same', dilation_rate=(1, 1),\n                           activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', \n                           kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, \n                           kernel_constraint=None, bias_constraint=None\n                          ),\n    tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None\n                             ),\n    tf.keras.layers.Conv2D(filters = 192, kernel_size = (3,3), strides=(1, 1), padding='same', dilation_rate=(1, 1),\n                           activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', \n                           kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, \n                           kernel_constraint=None, bias_constraint=None\n                          ),\n    tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None\n                             ),\n    tf.keras.layers.Conv2D(filters = 256, kernel_size = (2,2), strides=(1, 1), padding='same', dilation_rate=(1, 1),\n                           activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', \n                           kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, \n                           kernel_constraint=None, bias_constraint=None\n                          ),\n    tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None\n                             ),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(units = 10, activation = 'relu'),\n    tf.keras.layers.Dense(units = 5, activation = 'softmax')\n    \n    ])\n    \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x=train_generator, y=None, batch_size=None, epochs=5, verbose=1, callbacks=None,\n                    validation_split=None, validation_data=val_generator, shuffle=True, class_weight=None,\n                    sample_weight=None, initial_epoch=0, steps_per_epoch=None,\n                    validation_steps=None, validation_batch_size=None, validation_freq=1,\n                    max_queue_size=10, workers=1, use_multiprocessing=False\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x=train_generator, y=None, batch_size=None, epochs=5, verbose=1, callbacks=None,\n                    validation_split=None, validation_data=val_generator, shuffle=True, class_weight=None,\n                    sample_weight=None, initial_epoch=0, steps_per_epoch=None,\n                    validation_steps=None, validation_batch_size=None, validation_freq=1,\n                    max_queue_size=10, workers=1, use_multiprocessing=False\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}