{"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 all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nprint(os.listdir(\"../input\"))\nfrom keras.applications import ResNet50\nfrom keras.models import Model\nfrom keras.layers import Dense, GlobalAveragePooling2D, Dropout, Input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport keras\nimport csv\nimport gc\nimport cv2\n\n# Importing the libraries\n\nimport json\nimport math\nimport os\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom keras import layers\n# from keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint, EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv = \"../input/train.csv\"\ntest_csv = \"../input/test.csv\"\ntrain_dir = \"../input/train_images/\"\ntest_dir = \"../input/test_images/\"\nsize = 224 # input image size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(train_csv)\ndf_test = pd.read_csv(test_csv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def df_train_test_split_preprocess(df):\n    image_ids = df[\"id_code\"].values.tolist()\n    labels = df[\"diagnosis\"].values.tolist()\n    for i in range(len(image_ids)):\n        imgname = image_ids[i]\n        newname = str(imgname)+'.png'\n        image_ids[i] = newname\n    xtrain,xval,ytrain,yval = train_test_split(image_ids, labels, test_size = 0.1)\n    df_train = pd.DataFrame({\"id_code\":xtrain, \"diagnosis\":ytrain})\n    df_val = pd.DataFrame({\"id_code\":xval, \"diagnosis\":yval})\n    df_train[\"diagnosis\"] = df_train[\"diagnosis\"].astype('str')\n    df_val[\"diagnosis\"] = df_val[\"diagnosis\"].astype(\"str\")\n    print(\"Length of Training Data:\",len(df_train))\n    print(\"Length of Test Data:\",len(df_val))\n    return df_train, df_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train, df_val = df_train_test_split_preprocess(df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Plotting the ditribution of labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"no_dr= 0 \nmild=0\nmoderate=0\nsevere=0\nproliferative=0\nfor i in range(len(df)):\n    if df['diagnosis'][i] == 0:\n        no_dr+=1\n    if df['diagnosis'][i] == 1:\n        mild+=1\n    if df['diagnosis'][i] == 2:\n        moderate+=1\n    if df['diagnosis'][i] == 3:\n        severe+=1\n    if df['diagnosis'][i] == 4:\n        proliferative+=1\n        \nexplode = [0.1,0,0,0,0]\nlabels = 'no_dr','mild','moderate','severe','proliferative'\n\nsizes = [no_dr, mild, moderate, severe, proliferative]\n\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, explode = explode, labels=labels, autopct='%1.1f%%',\n       shadow=True, startangle=90)\nax1.axis('equal')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"CROPPING IMAGES\nDisplaying sample images cropped\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_to_show = ['07419eddd6be.png','0124dffecf29.png']\ndef get_cropped_image(image):\n    #img = cv2.blur(image,(2,2))\n    img = image\n    slice1Copy = np.uint8(img)\n    canny = cv2.Canny(slice1Copy, 0,50)\n    pts = np.argwhere(canny>0)\n    y1, x1 = pts.min(axis=0)\n    y2, x2 = pts.max(axis=0)\n    cropped_img = img[y1:y2, x1:x2]\n    cropped_img = cv2.resize(cropped_img,(size,size))\n    cropped_img = cropped_img.astype(\"float32\")*(1.)/255\n    return np.array(cropped_img)\n\nnames =[]\nsamples = []\ncropped_images = []\nfor i in sample_to_show:\n    path = train_dir+str(i)\n    img_ = cv2.imread(path)\n    samples.append(img_)\n    cropped_ = get_cropped_image(img_)\n    cropped_images.append(cropped_)\n\nfig = plt.figure(figsize=(5,5))\nax1 = fig.add_subplot(2,2,1)\nax1.title.set_text('original image')\nax1.axis(\"off\")\nplt.imshow(samples[0])\nax2 = fig.add_subplot(2,2,2)\nax2.title.set_text('croped image')\nax2.axis(\"off\")\nplt.imshow(cropped_images[0])\nax3 = fig.add_subplot(2,2,3)\nax3.title.set_text('original image')\nax3.axis('off')\nplt.imshow(samples[1])\nax4 = fig.add_subplot(2,2,4)\nax4.title.set_text('cropped image')\nax4.axis('off')\nplt.imshow(cropped_images[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def sample_original_images(df, cols=4, rows=3):\n    fig = plt.figure(figsize=(5*cols,4*rows))\n    path = train_dir\n    for i in range(cols*rows):\n        rand = np.random.randint(0,len(df))\n        image_name = df.loc[rand,'id_code']+\".png\"\n        img=cv2.imread(os.path.join(path,image_name))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        fig.add_subplot(rows, cols, i+1)\n        plt.title('image_name')\n        plt.imshow(img)\n        \n    plt.tight_layout()\n    \nsample_original_images(df)\n        ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#cropping:\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_image_from_gray(img, tol=7):\n    if img.ndim == 2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1), mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1), mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1 = img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2 = img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3 = img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n    #         print(img1.shape,img2.shape,img3.shape)\n            img = np.stack([img1,img2,img3],axis=-1)\n    #         print(img.shape)\n        return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def circle_crop(img):\n    img = crop_image_from_gray(img)\n    \n    heigh, width, depth = img.shape\n    largest_side = np.max((heigh, width))\n    img = cv2.resize(img, (largest_side, largest_side))\n    \n    height, width, depth = img.shape\n    \n    x = int(width / 2)\n    y = int(height / 2)\n    r = np.amin((x,y))\n    \n    circle_img = np.zeros((height, width), np.uint8)\n    cv2.circle(circle_img,(x,y), int(r), 1,thickness = -1)\n    \n    img = cv2.bitwise_and(img, img, mask=circle_img)\n    img = crop_image_from_gray(img)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_ben_color(path, sigmaX = 10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = circle_crop(image)\n    image = cv2.resize(image, (size, size))\n    image = cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)   \n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def process_images(path, size=size):\n    img = Image.open(path)\n    image = load_ben_color(path, sigmaX=20)\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#x_train, y_train, x_val, y_val = df_train['id_code'], df_train['diagnosis'], df_val['id_code'], df_val['diagnosis']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#code copied from above for sample change, only few changes made","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def sample_original_images(df, cols=4, rows=3):\n    fig = plt.figure(figsize=(5*cols,4*rows))\n    path = train_dir\n    for i in range(cols*rows):\n        rand = np.random.randint(0,len(df))\n        image_name = df.loc[rand,'id_code']+\".png\"\n        #img=cv2.imread(os.path.join(path,image_name))\n        \n        path_1=os.path.join(path,image_name)\n        img = load_ben_color(path_1, sigmaX=10) #40 0.20  20  0.50\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        fig.add_subplot(rows, cols, i+1)\n        plt.title(image_name)\n        plt.imshow(img)\n        \n    plt.tight_layout()\n    \nsample_original_images(df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"train data processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain=df['id_code']+'.png'\nxtest = df_test['id_code']+'.png'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"N = xtrain.shape[0]\nX_train_ = np.empty((N,size,size,3), dtype = np.uint8)\n\nfor i, image_id in enumerate(tqdm(xtrain)):\n    path_1 = os.path.join(train_dir,image_id)\n    X_train_[i,:,:,:] = process_images(path_1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#PROCESSING validation data"},{"metadata":{"trusted":true},"cell_type":"code","source":"N = xtest.shape[0]\nX_test_ = np.empty((N,size,size,3), dtype=np.uint8)\n\nfor i , image_id in enumerate(tqdm(xtest)):\n    path_1 = os.path.join(test_dir,image_id)\n    X_test_[i,:,:,:] = process_images(path_1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#making dummies of target variable"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train_ = pd.get_dummies(df['diagnosis']).values\n\nprint(X_train_.shape)\nprint(y_train_.shape)\nprint(X_test_.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Converting our target labels into multi-labels\n\n# y_train_multi = np.empty(y_train_.shape, dtype = y_train_.dtype)\n# y_train_multi[:, 4] = y_train_[:, 4]\n\n# for i in range(3, -1, -1):\n#     y_train_multi[:, i] = np.logical_or(y_train_[:, i], y_train_multi[:, i+1])\n\n# print(\"Original y_train:\", y_train_.sum(axis = 0))\n# print(\"Multilabel version:\", y_train_multi.sum(axis = 0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_train_multi[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Splitting our data into training and cross-validations sets\n\nx_train, x_val, y_train, y_val = train_test_split(X_train_, y_train_, test_size = 0.15, random_state = 77) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"create image data generator\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train_.shape, x_train.shape\n# x_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255,\n                            zoom_range=0.1,\n                            fill_mode='constant',\n                            cval=0,\n                            horizontal_flip=True,\n                            vertical_flip=True)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batches = train_datagen.flow(x_train, y_train, batch_size = 32, seed=2019)\nval_batches = val_datagen.flow(x_val, y_val, batch_size = 32, seed=2019)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import RMSprop, SGD, Adam\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier = Sequential()\n# First CONV-ReLU Layer\nclassifier.add(Conv2D(64, (3, 3), padding = 'same', input_shape = (size,size, 3)))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# Second CONV-ReLU Layer\nclassifier.add(Conv2D(64, (3, 3), padding = \"same\", input_shape = (size,size, 3)))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# Max Pooling with Dropout \nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n# classifier.add(Dropout(0.2))\n\n# 3rd set of CONV-ReLU Layers\nclassifier.add(Conv2D(128, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# 4th Set of CONV-ReLU Layers\nclassifier.add(Conv2D(128, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# Max Pooling with Dropout \nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n# classifier.add(Dropout(0.2))\n\n# 5th Set of CONV-ReLU Layers\nclassifier.add(Conv2D(256, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# 6th Set of CONV-ReLU Layers\nclassifier.add(Conv2D(256, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# Max Pooling with Dropout \nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n# classifier.add(Dropout(0.2))\n\n\n# 5th Set of CONV-ReLU Layers\nclassifier.add(Conv2D(256, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# 6th Set of CONV-ReLU Layers\nclassifier.add(Conv2D(256, (3, 3), padding=\"same\"))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n\n# Max Pooling with Dropout \nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n# classifier.add(Dropout(0.2))\n\n# First set of FC or Dense Layers\nclassifier.add(Flatten())\nclassifier.add(Dense(256))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n# classifier.add(Dropout(0.5))\n\n# Second set of FC or Dense Layers\nclassifier.add(Dense(256))\nclassifier.add(Activation('relu'))\n# classifier.add(BatchNormalization())\n# classifier.add(Dropout(0.5))\n\n# Final Dense Layer\nclassifier.add(Dense(5))\nclassifier.add(Activation(\"softmax\"))\n\nprint(classifier.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier.compile(loss = 'categorical_crossentropy',\n              optimizer = Adam(lr=0.0001),\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"                    \n# # checkpoint = ModelCheckpoint(\"../input/simpsons_little_vgg.h5\",\n# #                              monitor=\"val_loss\",\n# #                              mode=\"min\",\n# #                              save_best_only = True,\n# #                              verbose=1)\n\nearlystop = EarlyStopping(monitor = 'val_loss', \n                          min_delta = 0, \n                          patience = 5,\n                          verbose = 1,\n                          restore_best_weights = True)\n\n# reduce_lr = ReduceLROnPlateau(monitor = 'val_loss',\n#                               factor = 0.2,\n#                               patience = 3,\n#                               verbose = 1,\n#                               min_delta = 0.00001)\n\n# # we put our call backs into a callback list\ncallbacks = [earlystop]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = classifier.fit_generator(generator=batches, steps_per_epoch=batches.n,\n                             epochs=25,validation_data=val_batches,\n                             validation_steps=val_batches.n, callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# best = save_best_model(10, \"output\", 5, \".hdf5\")\n# model.load_weights(best)\n# model.save(\"best.h5s\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test_.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\npredprobs = classifier.predict_classes(X_test_)\n#np.sum([[0, 1], [0, 5]], axis=0)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predprobs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predprobs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\nfor i in predprobs:\n    predictions.append(i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test_.shape, X_train_.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id_code = df_test[\"id_code\"].values.tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for i in range(len(id_code)):\n#     imgid = id_code[i]\n#     newimgid = imgid[:-4]\n#     id_code[i] = newimgid","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nsubfile = pd.DataFrame({\"id_code\":id_code, \"diagnosis\":predictions})\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"subfile.to_csv('submission.csv',index=False)","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":1}