{"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\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        pass\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":"import tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nfrom sklearn.model_selection import train_test_split, StratifiedShuffleSplit\nfrom sklearn.preprocessing import MultiLabelBinarizer\nimport tensorflow_datasets as tfds\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport math\nimport glob\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_path = '../input/plant-pathology-2021-fgvc8/train_images'\ntest_image_path = '../input/plant-pathology-2021-fgvc8/test_images'\ntrain_df_path = '../input/plant-pathology-2021-fgvc8/train.csv'\ntest_df_path = '../input/plant-pathology-2021-fgvc8/sample_submission.csv'","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_path = '../input/resized-plant2021/img_sz_512'","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(train_df_path)\ndf_train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[\"labels\"]=df_train[\"labels\"].apply(lambda x:x.split(\" \"))\ndf_train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 512\nBATCH_SIZE = 128\nDATASET_SIZE = 18632\ntrain_size = int(0.9 * DATASET_SIZE)\n#16,768\nval_size = int(0.1 * DATASET_SIZE)\n\ndatagen=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n\ntrain_generator=datagen.flow_from_dataframe(\n    dataframe=df_train[:train_size],\n    directory=train_image_path,\n    x_col=\"image\",\n    y_col=\"labels\",\n    batch_size=BATCH_SIZE,\n    seed=42,\n    shuffle=False,\n    class_mode=\"categorical\",\n    classes=['complex', 'frog_eye_leaf_spot', 'healthy', 'powdery_mildew', 'rust', 'scab'],\n    target_size=(IMG_SIZE, IMG_SIZE)\n)\n\nvalid_generator=datagen.flow_from_dataframe(\n    dataframe=df_train[train_size:],\n    directory = train_image_path,\n    x_col=\"image\",\n    y_col=\"labels\",\n    batch_size=BATCH_SIZE,\n    seed=42,\n    shuffle=False,\n    class_mode=\"categorical\",\n    classes=['complex', 'frog_eye_leaf_spot', 'healthy', 'powdery_mildew', 'rust', 'scab'],\n    target_size=(IMG_SIZE,IMG_SIZE)\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)\n\n\n#base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')\nbase_model = tf.keras.models.load_model('../input/pretrainedmodel/MobileNet_512.h5')\nbase_model.trainable = False","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel = tf.keras.Sequential([\n      base_model,\n      layers.GlobalAveragePooling2D(),\n      layers.Dense(6, activation='sigmoid',activity_regularizer=tf.keras.regularizers.l2(0.01))\n    ])\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam')\n\nmodel.summary()\n\n\nhistory = model.fit(train_generator, epochs=15, validation_data = valid_generator)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"model.save('saved_model/model1')","metadata":{}},{"cell_type":"code","source":"test_list = os.listdir(test_image_path)\ncol_names = ['image']\ntest_df = pd.DataFrame(test_list, columns=col_names)\n\ntest_datagen=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\ntest_generator=test_datagen.flow_from_dataframe(\ndataframe=test_df,\ndirectory=test_image_path,\nx_col=\"image\",\nbatch_size=1,\nseed=42,\nshuffle=False,\nclass_mode=None,\ntarget_size=(IMG_SIZE,IMG_SIZE)\n)\n\ntest_generator.reset()\npred=model.predict(test_generator, verbose=1)\n\npred_bool = (pred >0.5)\npredictions=[]\nlabels = train_generator.class_indices\nlabels = dict((v,k) for k,v in labels.items())\nfor row in pred_bool:\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\nresults=pd.DataFrame({\"image\":filenames,\n                      \"labels\":predictions})\n\nresults = results.fillna(\"healthy\")\nresults.head()\n\nresults.to_csv(\"submission.csv\",index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}