{"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 os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport seaborn as sns\n\nfrom math import ceil\nfrom tqdm import tqdm\n\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, GlobalAveragePooling2D, Dropout\nfrom keras.optimizers import RMSprop, Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_path = \"/kaggle/input/\"\ntrain_img_path = os.path.join(data_path,'train_images')\ntest_img_path = os.path.join(data_path,'test_images')\ntrain_label_path = os.path.join(data_path,'train.csv')\ntest_label_path = os.path.join(data_path,'test.csv')\n\ndf_train = pd.read_csv(train_label_path)\ndf_test = pd.read_csv(test_label_path)\n\nprint(\"num of train images \", len(os.listdir(train_img_path)))\nprint(\"num of test images \",len(os.listdir(test_img_path)))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\ndf_train['diagnosis'].value_counts().plot(kind = 'bar')\nplt.title(\"Level of diagnosis\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nsamp = random.sample(df_train['id_code'].tolist(),3)\nsub=130\nfor i in range(len(samp)):\n    sub+=1\n    plt.figure(figsize=(15,15))\n    plt.subplot(sub)\n    file_path = \"../input/train_images/\"+samp[i]+\".png\"\n    img = cv2.imread(file_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nsamp = random.sample(df_train['id_code'].tolist(),3)\nsub=130\nfor i in range(len(samp)):\n    sub+=1\n    plt.figure(figsize=(15,15))\n    plt.subplot(sub)\n    file_path = \"../input/train_images/\"+samp[i]+\".png\"\n    img = cv2.imread(file_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_img=[]\ntrain_list = df_train[\"id_code\"].tolist()\nfor item in train_list:\n    file_path = \"../input/train_images/\"+str(item)+\".png\"\n    img = cv2.imread(file_path)\n    img = cv2.resize(img,(150,150))\n    #print(img)\n    df_train_img.append(img)\ndf_train_img = np.array(df_train_img, np.float32)/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test_img=[]\nfor item in df_test[\"id_code\"].tolist():\n    file_path = \"../input/test_images/\"+str(item)+\".png\"\n    img = cv2.imread(file_path)\n    img = cv2.resize(img,(150,150))\n    df_test_img.append(img)\ndf_test_img = np.array(df_test_img, np.float32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"making categories in target variable\n"},{"metadata":{"trusted":true},"cell_type":"code","source":" y_train = (df_train.iloc[:,1].values).astype('int32')\n# from keras.utils.np_utils import to_categorical\n# y_train = to_categorical(y_train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#splittin the train dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX = df_train_img\nY = y_train\nx_train, x_val, y_train, y_val = train_test_split(df_train_img, y_train, test_size = 0.15, random_state = 42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df_train_img.reshape(df_train_img.shape[0],150,150,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train_datagen = ImageDataGenerator(rescale = 1./255,\n#                                   shear_range = 0.2,\n#                                   zoom_range = 0.2,\n#                                   horizontal_flip = True)\n# test_datagen = ImageDataGenerator(rescale = 1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nfrom keras.preprocessing import image\ngen = image.ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batches = gen.flow(x_train, y_train, batch_size = 64)\nval_batches = gen.flow(x_val, y_val, batch_size = 64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier = Sequential()\nclassifier.add(Convolution2D(32, 3 ,3, input_shape = (150,150,3), activation  = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2,2)))\nclassifier.add(Convolution2D(32,3,3, activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2,2)))\nclassifier.add(Flatten())\nclassifier.add(Dense(output_dim = 75, activation = 'relu'))\nclassifier.add(Dense(output_dim = 5, activation = 'softmax'))\n\nclassifier.compile(optimizer = 'nadam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nhist = classifier.fit_generator(generator=batches, steps_per_epoch = batches.n,\n                             epochs=3, validation_data=val_batches,\n                             validation_steps=val_batches.n)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predictions.count_values()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = classifier.predict_classes(df_test_img,verbose=0)\nsudmissions = pd.DataFrame({'id_code':df_test.iloc[:,0].tolist(),\n                           'diagnosis': predictions})\nsudmissions.to_csv(\"submission.csv\", index = False, header = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":1}