{"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(\"../\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\n\ntrain_set = pd.read_csv('../input/train.csv')\ntest_set = pd.read_csv('../input/test.csv')\ntest_length = len(test_set)\ntrain_set = pd.get_dummies(train_set,columns = ['diagnosis'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_image_path = \"../input/train_images/\"\ntest_image_path = \"../input/test_images/\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(train_set.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.io import imread\nimport matplotlib.pyplot as plt\npath = train_image_path+train_set.iloc[2,0]+\".png\"\nimage = imread(path,as_gray=True)\nimg = imread(path)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(image,cmap='gray')\n\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_train_input(image):\n    path = train_image_path+image+\".png\"\n    img = imread(path,as_gray=True)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_test_input(image):\n    path = test_image_path+image+\".png\"\n    img = imread(path,as_gray=True)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_output(image):\n    df = train_set.loc[train_set['id_code'] == image]\n    df = df.iloc[:,1:]\n    return df.values[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.transform import resize,rotate\nimport cv2\ndef preprocess_input(image):\n    kernel = np.ones((5,5),np.uint8)\n    erosion = cv2.morphologyEx(image,cv2.MORPH_OPEN,kernel)\n    erosion = resize(erosion,(100,100),anti_aliasing=False)\n    erosion = rotate(erosion,np.random.randint(0,45))\n    return resize(image,(100,100),anti_aliasing=False)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef train_image_data_generator(train_set,batch_size):\n    while True:\n        # Select files (paths/indices) for the batch\n        batch_paths = np.random.choice(a = train_set.iloc[:,0], size = batch_size)\n        batch_input = []\n        batch_output = [] \n          \n          # Read in each input, perform preprocessing and get labels\n        for input_path in batch_paths:\n            input = get_train_input(input_path)\n            output = get_output(input_path)\n            input = preprocess_input(image=input)\n            input = np.reshape(input,(100,100,1))\n            batch_input += [ input ]\n            batch_output += [ output ]\n          # Return a tuple of (input,output) to feed the network\n        batch_x = np.array( batch_input )\n        batch_y = np.array( batch_output )\n        yield( batch_x, batch_y ) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def test_image_data_generator(batch,batch_size):\n        # Select files (paths/indices) for the batch\n    for chunks in batch:\n        batch_paths = chunks\n        batch_input = []\n            # Read in each input, perform preprocessing and get labels\n        input = get_test_input(batch_paths[0])\n        input = resize(image,(100,100),anti_aliasing=False)\n        input = np.reshape(input,(100,100,1))\n        batch_input += [ input ]\n        # Return a tuple of (input,output) to feed the network\n        batch_x = np.array( batch_input )\n                \n    return batch_x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Conv2D,Dense,MaxPool2D,Flatten\nfrom keras.models import Sequential\nbatch_size = 32\nmodel = Sequential()\nmodel.add(Conv2D(4,kernel_size = (3,3),padding = 'same',activation='relu',input_shape = (100,100,1)))\nmodel.add(Conv2D(32,kernel_size = (3,3),activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(64,activation = 'relu'))\nmodel.add(Dense(32,activation = 'relu'))\nmodel.add(Dense(5,activation = 'softmax'))\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics=[\"mae\",\"accuracy\"])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"generator = train_image_data_generator(train_set,batch_size)\n\nhistory = model.fit_generator(generator,steps_per_epoch = len(train_set)//batch_size,epochs= 15,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Loss :- \"+ str(history.history['loss'][0]))\nprint(\"Mean absolute error :- \"+ str(history.history['mean_absolute_error'][0]))\nmodel.save_weights('model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys\ntest_set = pd.read_csv('../input/test.csv',chunksize= 32)\nrow_list = []\nobj = {}\npred = pd.DataFrame(columns=['id_code','diagnosis'])\nfor chunks in test_set:\n    data = chunks.values\n    for item in data:\n        image = get_test_input(item[0])\n        kernel = np.ones((5,5),np.uint8)\n        input = resize(image,(100,100),anti_aliasing=False)\n        input = np.reshape(input,(1,100,100,1))\n        out = model.predict(input)\n        obj = {\n            'id_code':item[0],\n            'diagosis':np.argmax(out,axis=1)[0]\n        }\n        row_list.append(obj)\n        sys.stdout.write(str(len(row_list)))\n        sys.stdout.flush()\nfinal_pred = pd.DataFrame(row_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_pred.to_csv('submission.csv', index = False, header = True, sep = ',', encoding = 'utf-8')","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}