{"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2\nimport tensorflow.keras as keras\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom tensorflow.keras.layers import Input, Activation, Dropout, Flatten, Dense, BatchNormalization\nfrom tensorflow.keras.applications import VGG16, Xception, InceptionV3\nfrom tensorflow.keras.models import Model\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\n# for 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.config.list_physical_devices('GPU')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/plant-pathology-2021-fgvc8/train.csv')\ndf[\"labels\"]=df[\"labels\"].apply(lambda x:x.split(\" \")) \n#df['labels']=df['labels'].astype('category')\ndf","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path= '../input/resized-plant2021/img_sz_256/'\nimg_size = (150,150)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rescale=1./255,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n)\n\ntrain_generator=datagen.flow_from_dataframe(\n    dataframe=df[:17500],\n    directory=train_path,\n    x_col=\"image\",\n    y_col=\"labels\",\n    batch_size=32,\n    seed=42,\n    shuffle=True,\n    class_mode=\"categorical\",\n    target_size=img_size)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_generator=datagen.flow_from_dataframe(\n    dataframe=df[17500:],\n    directory=train_path,\n    x_col=\"image\",\n    y_col=\"labels\",\n    batch_size=32,\n    seed=42,\n    shuffle=True,\n    class_mode=\"categorical\",\n    target_size=img_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_generator=datagen.flow_from_dataframe(\n    dataframe=df[17500:],\n    directory=train_path,\n    x_col=\"image\",\n    y_col=\"labels\",\n    batch_size=32,\n    seed=42,\n    shuffle=False,\n    class_mode=\"categorical\",\n    target_size=img_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = InceptionV3(include_top=False,\n                      weights='../input/inceptionv3weights/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5',\n                      input_shape=(150, 150, 3))\n    \n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = base_model.layers[-1].output\nx = BatchNormalization()(x)\nx = Flatten()(x)\nx = Dense(1024,activation='relu')(x)\nx = Dropout(0.5)(x)\nx = Dense(512,activation='sigmoid')(x)\nx = Dropout(0.2)(x)\nx = Dense(256,activation='relu')(x)\npredictions=Dense(6,activation='sigmoid')(x)\n\nmodel = Model(inputs=base_model.input, outputs=predictions, name='Plants')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow_addons as tfa\nf1 = tfa.metrics.F1Score(num_classes=6, average='macro')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"opt = keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)\nmodel.compile(loss='binary_crossentropy',\n              optimizer=opt,\n              metrics=[f1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size=32\nepochs = 15","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"earlystop = tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\",\n                                             min_delta=0.01,\n                                             patience=3,\n                                             verbose=0,\n                                             mode=\"auto\",\n                                             baseline=None,\n                                             restore_best_weights=False,\n)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(train_generator,\n                              epochs=epochs,\n                              steps_per_epoch=train_generator.samples//train_generator.batch_size,\n                              validation_data=val_generator,\n                              validation_steps=val_generator.n//batch_size,\n                              shuffle=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in model.layers[:-6]:\n    layer.trainable = False","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = history.history['f1_score']\nval_acc = history.history['val_f1_score']\n\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs_range = range(15)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 10","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(train_generator,\n                              epochs=epochs,\n                              steps_per_epoch=train_generator.samples//train_generator.batch_size,\n                              validation_data=val_generator,\n                              validation_steps=val_generator.n//batch_size,\n                              shuffle=True)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_path= '../input/plant-pathology-2021-fgvc8/test_images'\nfiles = os.listdir(test_path)\nfiles.sort()\ntestdf= pd.DataFrame(files, columns=['Image'])\ntestdf\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagenTest = ImageDataGenerator(\n    rescale=1./255,\n)\n\nimg_size = (150,150)\ntest_generator=datagenTest.flow_from_dataframe(\n    dataframe=testdf,\n    directory=test_path,\n    x_col='Image',\n    y_col=None,\n    batch_size=64,\n    seed=42,\n    shuffle=False,\n    class_mode=None,\n    target_size=img_size\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.predict(test_generator)\nresults","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[results>0.50]=1\nresults[results<=0.50]=0\nresults","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=[]\nlabels = train_generator.class_indices\nlabels = dict((v,k) for k,v in labels.items())\nfor row in results:\n    l=[]\n    for index,cls in enumerate(row):\n        if cls:\n            l.append(labels[index])\n    predictions.append(\" \".join(l))\nfilenames=test_generator.filenames\ndfResults=pd.DataFrame({\"image\":filenames,\n                      \"labels\":predictions})\ndfResults.to_csv(\"submission.csv\",index=False)\ndfResults","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}