{"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input/densenet-169\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport json\nimport numpy as np\nimport os\nimport keras\nimport matplotlib.pyplot as plt\nfrom keras.layers import Dense,GlobalAveragePooling2D,Dropout\nfrom keras.applications import DenseNet169\nfrom keras.preprocessing import image\nfrom keras.applications.mobilenet import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import Callback,ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping\nfrom sklearn.metrics import cohen_kappa_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model=DenseNet169(weights = \"../input/densenet-169/DenseNet-BC-169-32-no-top.h5\",\n                       include_top=False\n                      )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=base_model.output\nx=GlobalAveragePooling2D()(x)\nx=Dropout(0.5)(x)\npreds=Dense(5, activation='sigmoid')(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Model(inputs=base_model.input,outputs=preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    loss='binary_crossentropy',\n    optimizer=Adam(lr=0.00001),\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ntrain_df[\"id_code\"]=train_df[\"id_code\"].apply(lambda x:x+\".png\")\ntrain_df['diagnosis'] = train_df['diagnosis'].astype(str)\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_classes = 5\nlbls = list(map(str, range(nb_classes)))\nbatch_size = 32\nimg_size = 224\nnb_epochs = 30","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n    rescale=1./255,\n    featurewise_center=True,\n    featurewise_std_normalization=True,\n    zca_whitening=True,\n    rotation_range=45,\n    width_shift_range=0.2, \n    height_shift_range=0.2,\n    horizontal_flip=True,\n    vertical_flip=True,\n    validation_split=0.1,   \n    zoom_range = 0.3,\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=\"../input/aptos2019-blindness-detection/train_images\",\n    x_col=\"id_code\",\n    y_col=\"diagnosis\",\n    batch_size=batch_size,\n    shuffle=True,\n    class_mode=\"categorical\",\n    classes=lbls,\n    target_size=(img_size,img_size),\n    subset='training')\n\nprint('break')\n\nvalid_generator=train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=\"../input/aptos2019-blindness-detection/train_images\",\n    x_col=\"id_code\",\n    y_col=\"diagnosis\",\n    batch_size=batch_size,\n    shuffle=True,\n    class_mode=\"categorical\", \n    classes=lbls,\n    target_size=(img_size,img_size),\n    subset='validation')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpoint = ModelCheckpoint(\n    'dense_net.h5', \n    monitor='val_loss', \n    verbose=0, \n    save_best_only=True, \n    save_weights_only=False,\n    mode='auto'\n)\n\nhistory = model.fit_generator(\n    generator=train_generator,\n    steps_per_epoch=30,\n    epochs=nb_epochs,\n    validation_data=valid_generator,\n    validation_steps = 30,\n    callbacks=[checkpoint]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['acc', 'val_acc']].plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sam_sub_df = pd.read_csv('../input/aptos2019-blindness-detection/sample_submission.csv')\nsam_sub_df[\"id_code\"]=sam_sub_df[\"id_code\"].apply(lambda x:x+\".png\")\nprint(sam_sub_df.shape)\nsam_sub_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_dataframe(  \n        dataframe=sam_sub_df,\n        directory = \"../input/aptos2019-blindness-detection/test_images\",    \n        x_col=\"id_code\",\n        target_size = (img_size,img_size),\n        batch_size = 1,\n        shuffle = False,\n        class_mode = None\n        )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict=model.predict_generator(test_generator, steps = len(test_generator.filenames))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames=test_generator.filenames\nresults=pd.DataFrame({\"id_code\":filenames,\n                      \"diagnosis\":np.argmax(predict,axis=1)})\nresults['id_code'] = results['id_code'].map(lambda x: str(x)[:-4])\nresults.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results.head()","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":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}