{"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":"from tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\nconfig=ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction=0.5\nconfig.gpu_options.allow_growth=True\nsession=InteractiveSession(config=config)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nfrom tensorflow.keras.optimizers import RMSprop,Adam\nimport numpy as np\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom keras import Model\nfrom os import getcwd\nfrom keras.layers import Dense, Activation, BatchNormalization\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.test.is_gpu_available(\n    cuda_only=False, min_cuda_compute_capability=None\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ModelCheckpoint,ReduceLROnPlateau\nearlyStopping = EarlyStopping(monitor='val_accuracy', patience = 15, verbose=0, mode='max')\nmcp_save_xc = ModelCheckpoint(filepath='mdl_wts.hdf5', save_best_only=True, monitor='val_accuracy', mode='max')\nmcp_save_ens = ModelCheckpoint(filepath='mdl_wts_en.h5', save_best_only=True, monitor='val_accuracy', mode='max')\nmcp_save_ens1 = ModelCheckpoint(filepath='mdl_wts_en1.h5', save_best_only=True, monitor='val_loss', mode='min')\nreduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', patience=5, verbose=1, min_delta=1e-4, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['label']=train_df['label'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nTRAINING_DIR = \"../input/cassava-leaf-disease-classification/train_images\"\ntrain_datagen = ImageDataGenerator(\n    rescale=1/255,\n    rotation_range=40,\n    width_shift_range=.2,\n    height_shift_range=.2,\n    shear_range=.2,\n    validation_split=0.05,\n    #zoom_range=.2,\n\n    horizontal_flip=True,\n    #fill_mode='nearest'\n)\ntrain_generator = train_datagen.flow_from_dataframe(dataframe=train_df,\n    directory = TRAINING_DIR,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    batch_size = 64,\n    subset = 'training',\n    class_mode='categorical',\n    shuffle = True,\n    target_size=(224,224)\n)\n\n\nvalidation_generator = train_datagen.flow_from_dataframe(dataframe=train_df,\n    directory = TRAINING_DIR,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    shuffle = True,\n    batch_size = 64,\n    subset = 'validation',\n    class_mode='categorical',\n    target_size=(224,224)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.inception_v3 import InceptionV3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pre_model = InceptionV3( input_shape = (224,224,3), include_top = False )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in pre_model.layers[:20]:\n  layer.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pre_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"last_layer = pre_model.get_layer('mixed7')\nprint('last layer output shape: ', last_layer.output_shape)\nlast_output = last_layer.output","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.optimizers import RMSprop,Adam\n\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom os import getcwd\nfrom keras.layers import Dense, Activation\n\nx = layers.Flatten()(last_output)\n\nx = layers.Dropout(0.5)(x)\n\nx = layers.Dense(1024, activation = \"relu\")(x)\n\nx = layers.Dense(1024, activation = \"relu\")(x)\n\nx = layers.Dropout(0.5)(x)\n\nx = layers.Dense(5, activation = \"softmax\")(x)\n\nmodel_new = Model(pre_model.input, x)\n\nmodel_new.compile(optimizer = Adam(lr=0.0001), \n              loss = 'categorical_crossentropy', \n              metrics = ['accuracy']\n             )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_xc = model_new.fit(\n      train_generator,  \n      callbacks = [ mcp_save_xc, reduce_lr_loss],\n      validation_data = validation_generator,\n      epochs = 15,\n      verbose = 1,\n )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\\","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}