{"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\nfor 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":"#reading CSV file\ntrain_valid_data = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/train.csv', dtype=str)\ntest_data = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/test.csv', dtype=str)\n\ndef append_ext(fn):\n    return fn+\".png\"\ntrain_valid_data[\"id_code\"]=train_valid_data[\"id_code\"].apply(append_ext)\ntest_data[\"id_code\"]=test_data[\"id_code\"].apply(append_ext)\n#splitting data set into traning and test keeping images in folder\n\ntrain_data = pd.DataFrame(train_valid_data.iloc[ 0:2930 , :].values)\ntrain_data.columns = ['filename' , 'class']\nvalid_data = pd.DataFrame(train_valid_data.iloc[ 2930:3662, :].values)\nvalid_data.columns = ['filename' , 'class']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Building CNN\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\nclassifier = Sequential()\n\n\nclassifier.add(Conv2D(64, (3, 3), input_shape = (150, 150, 3), activation = 'relu'))#Note- few values will be changed for black and white images\n\n# Step 2 - Pooling\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\n\n# Adding a second convolutional layer\nclassifier.add(Conv2D(64, (3, 3), activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\n\n# Step 3 - Flattening\nclassifier.add(Flatten())\n\n# Step 4 - Full connection\nclassifier.add(Dense(units = 256, activation = 'relu'))\nclassifier.add(Dense(units = 5, activation = 'softmax'))#Note- sigmoid function will be changed if output class is more than 2 # here i used softmax because the outcome class is more than 2\n\n# Compiling the CNN\nclassifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])#binary_crossentropy will be changed if o/p class is more than 2 #used categorical crossentropy as more than 2 class is there\n\"\"\"\n# Part 2 - Fitting the CNN to the images\nimport keras\nkeras.utils.np_utils.to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n                                   shear_range = 0.2,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = True)\n\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n        dataframe=train_data,\n        directory='/kaggle/input/aptos2019-blindness-detection/train_images',\n        x_col=\"filename\",\n        y_col=\"class\",\n        target_size=(150, 150),\n        batch_size=32,\n        class_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_dataframe(\n        dataframe=valid_data,\n        directory='/kaggle/input/aptos2019-blindness-detection/train_images',\n        x_col=\"filename\",\n        y_col=\"class\",\n        target_size=(150, 150),\n        batch_size=32,\n        class_mode='categorical')\n\n\"\"\"\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#training\n\"\"\"\nclassifier.fit_generator(\n        train_generator,\n        steps_per_epoch=1000,\n        epochs=10,\n        validation_data=validation_generator,\n        validation_steps=500)\n\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading trnined modoel\nfrom keras.models import load_model\nclassifier = load_model('/kaggle/input/trained-model-02/code_without_splitting_folder_and_train_test.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#making predictions\n\nfrom keras.preprocessing import image as image_utils\nimages = []\nfor root, dirs, files in os.walk('/kaggle/input/aptos2019-blindness-detection/test_images'):\n    for filename in files:\n        img = os.path.join(root, filename)\n        img = image_utils.load_img(img, target_size=(150, 150))\n        img = image_utils.img_to_array(img)\n        img = np.expand_dims(img, axis=0)\n        images.append(img)\n \n# stack up images list to pass for prediction\nimages = np.vstack(images)\nclasses = classifier.predict_classes(images, batch_size=10)\nprint(classes)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"################################making dataframe with the help of lists\n\nfinal_output = pd.DataFrame(np.column_stack([files, classes]), \n                               columns=['id_code', 'diagnosis'])\n\nfinal_output.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''#saving the model\nclassifier.save(\"code_without_splitting_folder_and_train_test.h5\")\n\nclassifier.save(\"code_without_splitting_folder_and_train_test\")\n'''","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}