{"cells":[{"metadata":{},"cell_type":"markdown","source":"experiment with the construction of features: blue-white veil, globules, etc.","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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 seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport gc\nimport pandas as pd\nfrom tensorflow.keras.models import Sequential, load_model, Model\nfrom tensorflow.keras.layers import Dense, Input, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import RMSprop, Adam, SGD \nfrom tensorflow.keras.metrics import TruePositives, FalsePositives, TrueNegatives, FalseNegatives, AUC, BinaryAccuracy, Precision, Recall\nimport cv2\nimport math\nfrom tensorflow.keras.regularizers import l1, l2, l1_l2\nimport shutil\nfrom tqdm import tqdm\nimport os\nfrom sklearn.utils import class_weight\nfrom sklearn.preprocessing import LabelEncoder","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/jpeg-melanoma-256x256/train.csv\")\ntest = pd.read_csv(\"../input/jpeg-melanoma-256x256/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.loc[train[\"sex\"].isnull(),[\"sex\"]] = \"male\"\ntrain.loc[train[\"age_approx\"].isnull(),[\"age_approx\"]] = 50\ntrain.loc[train[\"anatom_site_general_challenge\"].isnull(),[\"anatom_site_general_challenge\"]] = \"torso\"\ntrain[\"split\"] = 0\ntrain.loc[train[\"age_approx\"]<=40,[\"split\"]] = 1\ntrain.loc[(train[\"age_approx\"]>40) & (train[\"age_approx\"]<=76),[\"split\"]] = 2\ntrain.loc[train[\"age_approx\"]>76,[\"split\"]] = 3\ntrain[\"veil\"] = 0\ntrain[\"globuli\"] = 0\ntest[\"veil\"] = 0\ntest[\"globuli\"] = 0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<center>SEARCH FOR A BLUE AND WHITE VEIL</center>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lower_red= np.array([153,112,131])\nupper_red= np.array([215,161,170])\ndef get_blue_and_white_veil(im):\n    im = im[30:SHAPE-30,30:SHAPE-30]\n    mask = cv2.inRange(im, lower_red, upper_red)\n    res = cv2.bitwise_and(im,im, mask= mask)\n    thresh = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)\n    thresh = cv2.Canny( res, 50, 70)\n    contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n    jj=0\n    for c in contours:\n      if cv2.contourArea(c)>15:\n        jj+=1\n\n    blue_and_white_veil = 0  \n    if jj>6:\n      blue_and_white_veil=1\n    return  blue_and_white_veil","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<center>SEARCH FOR GLOBULES</center>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lower_red2= np.array([0,0,0])\nupper_red2= np.array([130,130,130])\n\ndef get_globuli2(im):\n    img = im[30:SHAPE-30,30:SHAPE-30].copy()\n    mask = cv2.inRange(img, lower_red2, upper_red2)\n    kernel = np.ones((2,2),np.uint8)\n    mask = cv2.dilate(mask,kernel, iterations=1)\n    contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n    jj=0\n    tl_f = 0\n    for c in contours:\n      box = cv2.minAreaRect(c)\n      ( tl, tr, br) = box\n      if cv2.contourArea(c)<70 and  abs(tl[0]-tl_f)>15:\n        jj+=1\n      tl_f = tl[0]\n    return jj","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SHAPE=256\nCROP_SIZE=15\ncenterXX=math.ceil((SHAPE-CROP_SIZE*2)/2)\ncenterYY=math.ceil((SHAPE-CROP_SIZE*2)/2)\nD=115\nTRAIN_DIR =  \"../input/jpeg-melanoma-256x256/train/\"\nTEST_DIR = \"../input/jpeg-melanoma-256x256/test/\"\ndef constructing_features(DIR,DATAFRAME):\n    for i, image_name in enumerate(tqdm(DATAFRAME[\"image_name\"])):\n        im = cv2.imread(DIR+image_name+\".jpg\")\n        im = im[CROP_SIZE:SHAPE-CROP_SIZE,CROP_SIZE:SHAPE-CROP_SIZE]\n        im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n        \n        mask = np.full((im.shape[0],im.shape[0]), 0, dtype=np.uint8)\n        cv2.circle(mask, (int(centerXX), int( centerYY)) , D , ( 255 , 0 , 0 ) , -1)\n        im = cv2.bitwise_or(im, im, mask=mask)\n        glob = get_globuli2(im)\n        veil =  get_blue_and_white_veil(im)\n        DATAFRAME.loc[i,\"veil\"] = veil\n        DATAFRAME.loc[i,\"globuli\"] = glob\nconstructing_features(TRAIN_DIR,train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_c = train.copy()\ntrain_split = 0\ntrain_val_split = 0\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=6)\nfor train_index, test_index in split.split(train_c,train_c[\"target\"]):\n    train_split = train_c.loc[train_index].copy()\n    train_val_split = train_c.loc[test_index].copy()\n    train_split.drop([\"split\"], axis=1, inplace=True)\n    train_val_split.drop([\"split\"], axis=1, inplace=True)\ntrain_x = train_split[[\"age_approx\",\"veil\",\"globuli\",\"width\",\"height\"]]\ntrain_y = train_split[\"target\"]\nval_x = train_val_split[[\"age_approx\",\"veil\",\"globuli\",\"width\",\"height\"]]\nval_y = train_val_split[\"target\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"METRICS = [\n      TruePositives(name='tp'),\n      FalsePositives(name='fp'),\n      TrueNegatives(name='tn'),\n      FalseNegatives(name='fn'), \n      BinaryAccuracy(name='accuracy'),\n      AUC(name='auc'),\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CW = class_weight.compute_class_weight('balanced',\n                                                 np.unique(train_split[\"target\"]),\n                                                 train_split[\"target\"])\nclases = [0,1]\nclass_weights = dict(zip(clases,CW))\nclass_weights","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"table_input = Input(shape=(train_x.shape[1]))\nd = Dense(300, activation=\"elu\")(table_input)\nd = BatchNormalization()(d)\nd = Dropout(0.2)(d)\nd = Dense(100, activation=\"elu\")(d)\nout = Dense(1, activation=\"sigmoid\")(d)\nmodel = Model(table_input,out)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=Adam(learning_rate=1e-4), metrics=METRICS)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hit = model.fit(x = train_x, y= train_y, validation_data=(val_x, val_y), epochs=10, class_weight=class_weights)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"constructing_features(TEST_DIR,test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_x = test[[\"age_approx\",\"veil\",\"globuli\",\"width\",\"height\"]]\npredictions = model.predict(test_x)\ntest[\"target\"] = predictions\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_sub = test[[\"image_name\",\"target\"]]\ntest_sub.to_csv(\"submission33.csv\", index=False, line_terminator=\"\\n\")","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}