{"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\"))\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 cv2\nX_img=[]\ny_p=[]\ndef create_training_set(label,path):\n    img =cv2.imread(path,cv2.IMREAD_COLOR)\n    img =cv2.resize(img,(150,150))\n    X_img.append(np.array(img))\n    y_p.append(str(label))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv('../input/train.csv')\nX = df_train['id_code']\ny = df_train['diagnosis']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nTRAIN_DIR ='../input/train_images'\nfor id_code,diagnosis in tqdm(zip(X,y)):\n    path =os.path.join(TRAIN_DIR,'{}.png'.format(id_code))\n    create_training_set(diagnosis,path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\nY =to_categorical(y_p)\nX=np.array(X_img)\nX=X/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_valid,Y_train,Y_valid = train_test_split(X,Y,test_size=0.2,random_state=22)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Feature Extraction**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfeat_extraction = ImageDataGenerator(featurewise_center=True,\n    featurewise_std_normalization=True,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True)\nfeat_extraction.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"***Modelling***"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(150,150,3)))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(GlobalAveragePooling2D())\n\nmodel.add(Dense(5, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.optimizers import Adam\nmodel.compile(optimizer= Adam(lr=0.01), loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size=100\nepochs=10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint\n\ncheckpointer =  ModelCheckpoint(filepath= 'CNN_keras.hdf5', verbose=1, save_best_only=True)\n\nmodel.fit_generator(feat_extraction.flow(X_train, Y_train, batch_size=batch_size),\n          epochs= epochs, validation_data=(X_valid, Y_valid),\n          callbacks= [checkpointer], verbose=1, steps_per_epoch=X_train.shape[0]//batch_size )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('../input/test_images/')[0:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_image = cv2.imread('../input/test_images/3d4d693f7983.png', cv2.IMREAD_COLOR)\ntest_image = cv2.resize(test_image, (150,150))\nimport matplotlib.pyplot as plt\n\nplt.imshow(test_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_X = np.array(test_image)\ntest_X = test_X/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_test= model.predict(np.expand_dims(test_X,axis=0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('../input/test.csv')\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ids = test_df['id_code']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images = []\ndef create_test_set(path):\n    img = cv2.imread(path,cv2.IMREAD_COLOR)\n    img = cv2.resize(img, (150,150))\n\n    test_images.append(np.array(img))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for id_code in tqdm(test_ids):\n    path = os.path.join('../input/test_images','{}.png'.format(id_code))\n    create_test_set(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_X=np.array(test_images)\ntest_X=test_X/255\npred=model.predict(test_X)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = np.argmax(pred, axis=1)\npred\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(pred)","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":4}