{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport cv2\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.optimizers import Adam, RMSprop\nfrom tensorflow.keras.applications import VGG16,ResNet50,InceptionV3,VGG19,InceptionResNetV2\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, LearningRateScheduler","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['label'] = df['label'].apply(lambda x: str(x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = df.image_id\ny = df.label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain, test = train_test_split(df, test_size = 0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n          rotation_range = 15,\n          width_shift_range = 0.1,\n          height_shift_range = 0.1,\n          shear_range = 0.1,\n          zoom_range = 0.1,\n          horizontal_flip = True,\n          fill_mode = \"nearest\",\n          validation_split = 0.15)\n\ntest_datagen=ImageDataGenerator(rescale=1.)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32\ntrain_generator=datagen.flow_from_dataframe(\n                dataframe=train,\n                directory= '../input/cassava-leaf-disease-classification/train_images',\n                x_col='image_id',\n                y_col='label',\n                subset=\"training\",\n                batch_size=batch_size,\n                shuffle=True,\n                class_mode=\"categorical\",\n                target_size=(256,256))\n\nval_gen=datagen.flow_from_dataframe(\n                dataframe=train,\n                directory= '../input/cassava-leaf-disease-classification/train_images',\n                x_col='image_id',\n                y_col='label',\n                subset=\"validation\",\n                batch_size=batch_size,\n                shuffle=False,\n                class_mode=\"categorical\",\n                target_size=(256,256))\n\n# Create a data generator for test images\n\n\ntest_generator=test_datagen.flow_from_dataframe(\n               dataframe=test,\n               directory= '../input/cassava-leaf-disease-classification/train_images',\n               x_col='image_id',\n               y_col='label',\n               batch_size=batch_size,\n               shuffle=False,\n               class_mode='categorical',\n               target_size=(256,256))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weights = ('../input/classifier/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base = InceptionV3(weights = weights, include_top = False, input_shape=(256, 256, 3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"top = base.output\ntop = layers.AveragePooling2D(pool_size = (4,4))(top)\ntop = layers.Flatten(name= 'flatten')(top)\ntop = layers.Dense(256, activation = \"relu\")(top)\ntop = layers.Dropout(0.3)(top)\ntop = layers.Dense(256, activation = \"relu\")(top)\ntop = layers.Dropout(0.3)(top)\n#top = layers.Dense(256, activation = \"relu\")(top)\n#top = layers.Dropout(0.3)(top)\ntop = layers.Dense(5, activation = 'softmax')(top)\nmodel = Model(inputs = base.input, outputs = top)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics= [\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#earlystopping = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10)\ncheckpointer = ModelCheckpoint(filepath=\"./classifier-InceptionV3-weights1.hdf5\", verbose=1, save_best_only=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nepoch = 50\nhistory = model.fit(\n          train_generator,\n          steps_per_epoch= train_generator.n // batch_size,\n          epochs = epoch,\n          validation_data= val_gen,\n          validation_steps= val_gen.n // batch_size,\n          callbacks=[checkpointer])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model =tf.keras.models.load_model('./classifier-InceptionV3-weights1.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(test_generator, steps=101)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred =model.predict(test_generator,steps=101)\ny_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction = []\nfor i in range(len(y_pred)):\n  c = np.argmax(y_pred[i])\n  prediction.append(c)\nprediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.label = prediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":false,"_kg_hide-output":true,"collapsed":true},"cell_type":"code","source":"test.set_index('image_id',inplace = True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.to_csv(\".//submission.csv\")","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}