{"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 os\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport keras as ks\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, Dense, MaxPooling2D, Flatten, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom PIL import Image\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\n\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\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":"train_original = pd.read_csv(\"../input/siim-isic-melanoma-classification/train.csv\", dtype=str)\ntest_original = pd.read_csv('../input/siim-isic-melanoma-classification/test.csv', dtype=str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train_original)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_original.head(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_original.head(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# original image\n\nimage = Image.open(\"../input/siim-isic-melanoma-classification/jpeg/test/ISIC_0052060.jpg\")\nimgplot = plt.imshow(image)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# resized image\n\nimage = Image.open(\"../input/siic-isic-224x224-images/test/ISIC_0052060.png\")\nimgplot = plt.imshow(image)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_original","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"part_true = train_original[train_original[\"target\"] == '1']\npart_false = train_original[train_original[\"target\"] == '0'].sample(len(part_true) * 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(part_true))\nprint(len(part_false))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_balanced = pd.concat([part_true, part_false])\nlen(train_balanced)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a = train_balanced.sample(round(len(train_balanced) * 0.7))\nb = train_balanced[~train_balanced[\"image_name\"].isin(a[\"image_name\"])]\nprint(len(a))\nprint(len(b))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# t = train_balanced.sample(n=300)\nt = train_balanced\nt[\"file_name\"] = t[\"image_name\"] + \".png\"\n\n            \ntrain_set = t.sample(round(len(t) * 0.7))\nval_set = t[~t[\"image_name\"].isin(train_set[\"image_name\"])]\n\n\n# val_set_mock = t[190:200]\n# val_set_mock_file_names = np.array(\"../input/siic-isic-224x224-images/train/\" + val_set_mock[\"file_name\"])\n# val_set_mock_images = np.array([np.array(Image.open(fname)) for i, fname in enumerate(val_set_mock_file_names)])\n# val_set_mock_labels = val_set_mock[\"diagnosis\"]\n\n\ntest_set = test_original.sample(n=500)\ntest_set[\"file_name\"] = test_set[\"image_name\"] + \".png\"\n\nimages = np.array(\"../input/siic-isic-224x224-images/test/\" + test_set[\"file_name\"])\ntest_set_images = np.array([np.array(Image.open(fname)) for i, fname in enumerate(images)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(train_set))\nprint(len(val_set))\n# print(len(val_set_mock))\nprint(len(test_set))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Number of categories\ntruth = train_set[\"diagnosis\"].unique()\ntruth","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width, img_height = 224, 224\nnb_train_samples = len(train_set)\nnb_validation_samples = len(val_set)\nepochs = 10\nbatch_size = 64\nn_classes = truth.size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    zoom_range=0.2,\n    rotation_range = 5,\n    horizontal_flip=True)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = train_set, \n    directory = \"../input/siic-isic-224x224-images/train\", \n    x_col = \"file_name\", \n    # y_col = \"diagnosis\", \n    y_col = \"target\",\n    # class_mode = \"categorical\", \n    class_mode = \"binary\", \n    target_size = (img_width, img_height), \n    batch_size = batch_size,\n    validate_filenames = False)\n\n\nval_datagen = ImageDataGenerator(rescale=1. / 255)\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe = val_set, \n    directory = \"../input/siic-isic-224x224-images/train\", \n    x_col = \"file_name\",\n    # y_col = \"diagnosis\",\n    y_col = \"target\",\n    # class_mode = \"categorical\", \n    class_mode = \"binary\", \n    target_size = (img_width, img_height), \n    batch_size = batch_size,\n    validate_filenames = False)","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=test_set,\n    directory=\"../input/siic-isic-224x224-images/test\",\n    x_col=\"file_name\",\n    y_col=None,\n    batch_size=1,\n    seed=420,\n    class_mode=None,\n    target_size=(img_width, img_height),\n    validate_filenames = False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = ks.applications.densenet.DenseNet169(\n    include_top=False, \n    input_shape=(img_width,img_height,3), \n    weights = '../input/densenet-keras/DenseNet-BC-169-32-no-top.h5')\n\nbase_model.trainable = True","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"add_model = Sequential()\nadd_model.add(Flatten(input_shape=base_model.output_shape[1:]))\nadd_model.add(Dense(256, activation='relu'))\nadd_model.add(Dropout(0.2))\nadd_model.add(Dense(1, activation='softmax'))\n\nmodel = Model(inputs = base_model.input, outputs = add_model(base_model.output))\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy', \n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=val_generator, \n    validation_steps=nb_validation_samples // batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate_generator(val_generator)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict=model.predict_generator(test_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(\n    {'image_name': test_set[\"image_name\"], 'target': predict.flatten()},\n    columns = ['image_name', 'target']\n)\nsubmission.to_csv('sSubmission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# prediction = model.predict(val_set_mock_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# p = np.round(prediction)\n# indexes = np.where(p == 1)[1]\n# comparisons = (truth[indexes]) == val_set_mock_labels\n# true_predictions = np.sum(comparisons)\n# accuracy = true_predictions * 100 / len(val_set_mock_labels)\n# accuracy","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}