{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import math, re , os\nimport tensorflow as tf\nimport json\nimport cv2\nimport seaborn as sn\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#from kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial \nfrom sklearn.model_selection import train_test_split\nprint(\"tensorflow version\" + tf.__version__)\n\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import models, layers\nfrom PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"BASE_DIR = \"../input/cassava-leaf-disease-classification\"","execution_count":null,"outputs":[]},{"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":"# shape of 1st 300 images\nimg_shapes = {}\nfor image_name in os.listdir(os.path.join(BASE_DIR, \"train_images\"))[:300]:\n    image = cv2.imread(os.path.join(BASE_DIR, \"train_images\", image_name))\n    img_shapes[image.shape] = img_shapes.get(image.shape, 0) + 1 \n\nprint(img_shapes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(BASE_DIR , \"train.csv\"))\ndf_train[\"class_name\"] = df_train[\"label\"].map(map_classes)\n\ndf_train[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10, 5))\nsn.countplot(y=\"class_name\", data=df_train);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Main parameters\nBATCH_SIZE = 8\nSTEPS_PER_EPOCH = len(df_train)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(df_train)*0.2 / BATCH_SIZE\nEPOCHS = 20\nTARGET_SIZE = 512","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.label = df_train.label.astype('str')\n\ntrain_datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split = 0.2,\n                                     rescale = 1./255,\n                                     rotation_range = 45,\n                                     zoom_range = 0.2,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'nearest',\n                                     shear_range = 0.1,\n                                     height_shift_range = 0.1,\n                                     width_shift_range = 0.1)\n\ntrain_generator = train_datagen.flow_from_dataframe(df_train,\n                         directory = os.path.join(BASE_DIR, \"train_images\"),\n                         subset = \"training\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")\n\n\nvalidation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split = 0.2)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(df_train,\n                         directory = os.path.join(BASE_DIR, \"train_images\"),\n                         subset = \"validation\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n    conv_base = EfficientNetB0(include_top = False, weights = None,\n                               input_shape = (TARGET_SIZE, TARGET_SIZE, 3))\n    model = conv_base.output\n    model = layers.GlobalAveragePooling2D()(model)\n    model = layers.Dense(5, activation = \"softmax\")(model)\n    model = models.Model(conv_base.input, model)\n\n    model.compile(optimizer = Adam(lr = 0.001),\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"acc\"])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights('../input/weight1/myweights3.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, \n                              patience = 2, min_delta = 0.001, \n                              mode = 'min', verbose = 1)\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_generator,\n    validation_steps = VALIDATION_STEPS,\n    callbacks = [early_stop, reduce_lr]\n)\n\nmodel.save('./myEffNetB0_512_8__3.h5')\nmodel.save_weights('./myweights4.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss = pd.read_csv(os.path.join(BASE_DIR, \"sample_submission.csv\"))\nss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = []\n\nfor image_id in ss.image_id:\n    image = Image.open(os.path.join(BASE_DIR,  \"test_images\", image_id))\n    image = image.resize((TARGET_SIZE, TARGET_SIZE))\n    image = np.expand_dims(image, axis = 0)\n    preds.append(np.argmax(model.predict(image)))\n\nss['label'] = preds\nss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.to_csv('submission.csv', index = False)","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}