{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install split_folders","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport splitfolders\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D , Flatten\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras import metrics\nimport cv2\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm\nfrom keras.preprocessing import image\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom keras import losses, utils\nfrom keras.models import Model\nfrom keras.models import Sequential\nfrom keras.layers.merge import concatenate\nfrom keras.optimizers import Adam, RMSprop, SGD\nfrom keras.utils import to_categorical, plot_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Activation, Flatten, BatchNormalization\nfrom keras.callbacks import LearningRateScheduler, History, ModelCheckpoint, TensorBoard\nfrom keras.layers import Input, InputLayer, Conv2D, MaxPooling2D, Dropout, Dense, AveragePooling2D\nfrom keras.applications import VGG19\n\n!pip install patool\nimport patoolib\nfrom sklearn.utils import class_weight\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\n\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n# Input data files are available in the read-only \"../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# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs('dataset')\nos.makedirs('dataset/Training_set')\nos.makedirs('dataset/validation')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_loc = '../input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images/gaussian_filtered_images/'\n\nsplitfolders.ratio(img_loc, output='dataset', seed=1, ratio=(0.8, 0.2))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path = 'dataset/train/'\nvalid_path = 'dataset/val/'\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls dataset\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_batches = ImageDataGenerator(rescale=1./255)\\\n.flow_from_directory(\n    directory=train_path,target_size=(224, 224))\n\n\nvalid_batches = ImageDataGenerator(rescale=1./255)\\\n.flow_from_directory(\n    directory=valid_path,target_size=(224, 224))\n\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgs, labels = next(train_batches)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(imgs[9])\nprint(labels[9])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg16_model = tf.keras.applications.vgg16.VGG16()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg16_model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in vgg16_model.layers[:-1]:\n  model.add(layer)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in model.layers:\n  layer.trainable = False","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"model.add(Dense(units=5 , activation='softmax'))\nmodel.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in model.layers[-10:]:\n    layer.trainable = True\n    print(\"Layer '%s' is trainable\" % layer.name)  \n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(learning_rate=0.0001) , metrics=['accuracy'] , loss='categorical_crossentropy')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint = ModelCheckpoint(\"vgg16_DR.h5\", monitor='val_accuracy', verbose=1, \n                             save_best_only=True, save_weights_only=False, mode='auto')\nearly = EarlyStopping(monitor='val_accuracy', min_delta=0, patience=20, verbose=1, mode='auto')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from collections import Counter\ncounter = Counter(train_batches.classes)                       \nmax_val = float(max(counter.values()))   \nclass_weights = {class_id : max_val/num_images for class_id, num_images in counter.items()}\nclass_weights","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = model.fit(train_batches, steps_per_epoch=train_batches.samples//train_batches.batch_size, validation_data=valid_batches, \n                 class_weight=class_weights, validation_steps=valid_batches.samples//valid_batches.batch_size, \n                 epochs=30,callbacks=[checkpoint,early])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv('../input/diabetic-retinopathy-detection/sampleSubmission.csv.zip')\n\ntest.head()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_image_dir = os.path.join('../input/diabetic-retinopathy-detection')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test['path'] = retina_df['image'].map(lambda x: os.path.join(base_image_dir,\n                                                         '{}.jpeg'.format(x)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image = []\nPath = '../input/diabetic-retinopathy-detection/sample.zip'\nfor i in tqdm(range(10)):\n    img = image.load_img(test['Path'][i], target_size=(28,28,3))\n    img = image.img_to_array(img)\n    img = img/255\n    train_image.append(img)\nX = np.array(train_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls -lh","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Nmodel = Sequential()\nNmodel = model","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Nmodel.load_weights('vgg16_DR.h5')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Nmodel.get_weights()","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#../input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images/gaussian_filtered_images/Mild/0024cdab0c1e.png\n#label= 1\nfrom keras.preprocessing import image\nimport numpy as np\n\n\ntrain_image = []\n\nimg = image.load_img('../input/diabetic-retinopathy-224x224-gaussian-filtered/gaussian_filtered_images/gaussian_filtered_images/Mild/0024cdab0c1e.png', target_size=(224,224,3))\nimg = image.img_to_array(img)\nimg = img/255\ntrain_image.append(img)\nX = np.array(train_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = np.expand_dims(imgs[9], axis=0)\nprint(image)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(labels[9])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = np.array(labels[9])\n[np.where(y)[0][0] ]\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = Nmodel.predict( image ,verbose=1)\nprint(predictions)\np = np.argmax(predictions,axis=-1)\nfor i in p:\n    print(i)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import FileLink\nFileLink('vgg16_DR.h5')\n","metadata":{"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]}]}