{"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":"# 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\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","execution":{"iopub.status.busy":"2023-06-11T00:23:54.300279Z","iopub.execute_input":"2023-06-11T00:23:54.300729Z","iopub.status.idle":"2023-06-11T00:23:58.421099Z","shell.execute_reply.started":"2023-06-11T00:23:54.300640Z","shell.execute_reply":"2023-06-11T00:23:58.419595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport cv2\nimport os\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.utils import img_to_array\nfrom keras.utils import np_utils\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.models import Sequential","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:24:43.065051Z","iopub.execute_input":"2023-06-11T00:24:43.066266Z","iopub.status.idle":"2023-06-11T00:24:50.235158Z","shell.execute_reply.started":"2023-06-11T00:24:43.066212Z","shell.execute_reply":"2023-06-11T00:24:50.233549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = []\nlabels = []","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:24:53.160478Z","iopub.execute_input":"2023-06-11T00:24:53.161491Z","iopub.status.idle":"2023-06-11T00:24:53.166502Z","shell.execute_reply.started":"2023-06-11T00:24:53.161449Z","shell.execute_reply":"2023-06-11T00:24:53.165227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_Images(label,path):\n    img=cv2.imread(path,cv2.IMREAD_COLOR)\n    try:\n      img_res=cv2.resize(img,(256,256))\n      img_array = img_to_array(img_res)\n      img_array = img_array/255.0\n      dataset.append(img_array)\n      if str(label) == '0':\n        labels.append('0')\n      elif str(label) == '1' :\n            labels.append('1')\n      elif str(label) == '2' :\n            labels.append('2')\n      elif str(label) == '3' :\n            labels.append('3')\n      else :\n            labels.append('4')\n    except:\n      print(\"error\")","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:24:55.976216Z","iopub.execute_input":"2023-06-11T00:24:55.976624Z","iopub.status.idle":"2023-06-11T00:24:55.986089Z","shell.execute_reply.started":"2023-06-11T00:24:55.976589Z","shell.execute_reply":"2023-06-11T00:24:55.984797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_Data = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/train.csv\")\ntrain_Data.head()","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:24:58.672284Z","iopub.execute_input":"2023-06-11T00:24:58.672689Z","iopub.status.idle":"2023-06-11T00:24:58.709924Z","shell.execute_reply.started":"2023-06-11T00:24:58.672657Z","shell.execute_reply":"2023-06-11T00:24:58.708664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id_code_Data = train_Data['id_code']\ndiagnosis_Data = train_Data['diagnosis']","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:25:01.788589Z","iopub.execute_input":"2023-06-11T00:25:01.789040Z","iopub.status.idle":"2023-06-11T00:25:01.798787Z","shell.execute_reply.started":"2023-06-11T00:25:01.789002Z","shell.execute_reply":"2023-06-11T00:25:01.797492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for id_code,diagnosis in tqdm(zip(id_code_Data,diagnosis_Data)):\n    path = os.path.join('/kaggle/input/aptos2019-blindness-detection/train_images','{}.png'.format(id_code))\n    prepare_Images(diagnosis,path)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:25:05.104723Z","iopub.execute_input":"2023-06-11T00:25:05.105541Z","iopub.status.idle":"2023-06-11T00:32:22.996535Z","shell.execute_reply.started":"2023-06-11T00:25:05.105485Z","shell.execute_reply":"2023-06-11T00:32:22.994707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def crop_image_from_gray(img,tol=7):\n    if img.ndim ==2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n    #         print(img1.shape,img2.shape,img3.shape)\n            img = np.stack([img1,img2,img3],axis=-1)\n    #         print(img.shape)\n        return img\ndef preprocess_image(path, sigmaX=10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image=CLAHEgreen(image)\n        \n    return image\ndef CLAHEgreen(image):\n    green=image[:, :, 1]\n    clipLimit = 2.0\n    tileGridSize = (8,8)\n    clahe=cv2.createCLAHE(clipLimit = clipLimit, tileGridSize = tileGridSize)\n    cla=clahe.apply(green)\n#     cla=clahe.apply(cla)\n    img=cv2.merge((cla,cla,cla))\n    \n    return img","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:29.744736Z","iopub.execute_input":"2023-06-11T00:32:29.745233Z","iopub.status.idle":"2023-06-11T00:32:29.767364Z","shell.execute_reply.started":"2023-06-11T00:32:29.745193Z","shell.execute_reply":"2023-06-11T00:32:29.766320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\ndef get_histograms(df, columns=3, rows=2):\n    fig = plt.figure(figsize=(3 * columns, 4 * rows))\n    for i in range(columns * rows):\n        img_path = df.loc[i,'id_code']\n        img_id = df.loc[i,'diagnosis']\n        img = cv2.imread(f'../kaggle/input/aptos2019-blindness-detection/train_images/{img_path}.png')\n        ax = fig.add_subplot(rows, columns, i + 1)\n        ax.set_title(f'ID: {img_id}')\n        plt.hist(img.flatten(), 256, [0, 256], color='r')\n        ax.remove()","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:33.704921Z","iopub.execute_input":"2023-06-11T00:32:33.705365Z","iopub.status.idle":"2023-06-11T00:32:33.715560Z","shell.execute_reply.started":"2023-06-11T00:32:33.705328Z","shell.execute_reply":"2023-06-11T00:32:33.714338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = np.array(dataset)\nlabel_arr = np.array(labels)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:39.018362Z","iopub.execute_input":"2023-06-11T00:32:39.018830Z","iopub.status.idle":"2023-06-11T00:32:40.257154Z","shell.execute_reply.started":"2023-06-11T00:32:39.018791Z","shell.execute_reply":"2023-06-11T00:32:40.255718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_histograms(train_Data)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:41.904766Z","iopub.execute_input":"2023-06-11T00:32:41.905465Z","iopub.status.idle":"2023-06-11T00:32:42.522629Z","shell.execute_reply.started":"2023-06-11T00:32:41.905418Z","shell.execute_reply":"2023-06-11T00:32:42.520644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\n\ndef preprocess_image(path, sigmaX=10):\n    # Load image using PIL.Image.open()\n    image = np.array(Image.open(path))\n    \n    # Convert color space using cv2.cvtColor()\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    \n    # Check if the image is empty\n    if image.size == 0:\n        raise ValueError(\"Image is empty or could not be loaded\")\n    \n    # Apply Gaussian blur using cv2.GaussianBlur()\n    image = cv2.GaussianBlur(image, (5, 5), sigmaX)\n    image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0, 0), sigmaX), -4, 128)\n    \n    # Convert color space back to RGB using cv2.cvtColor()\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    return image","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:45.501009Z","iopub.execute_input":"2023-06-11T00:32:45.501424Z","iopub.status.idle":"2023-06-11T00:32:45.511178Z","shell.execute_reply.started":"2023-06-11T00:32:45.501390Z","shell.execute_reply":"2023-06-11T00:32:45.510061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 256   # Define the constant\n\ndef preprocess_image(path, sigmaX=10):\n    # Load image using cv2.imread()\n    image = cv2.imread(path)\n    ...\n    \nN = train_Data.shape[0]\nx_train = np.empty((N, IMG_SIZE, IMG_SIZE, 3), dtype=np.uint8)   # Use the constant","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:49.674038Z","iopub.execute_input":"2023-06-11T00:32:49.674449Z","iopub.status.idle":"2023-06-11T00:32:49.682481Z","shell.execute_reply.started":"2023-06-11T00:32:49.674416Z","shell.execute_reply":"2023-06-11T00:32:49.680539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = pd.get_dummies(train_Data['diagnosis']).values\n\n\nprint(y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:52.432893Z","iopub.execute_input":"2023-06-11T00:32:52.433340Z","iopub.status.idle":"2023-06-11T00:32:52.454440Z","shell.execute_reply.started":"2023-06-11T00:32:52.433303Z","shell.execute_reply":"2023-06-11T00:32:52.452823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 4] = y_train[:, 4]\n\nfor i in range(3, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:55.897045Z","iopub.execute_input":"2023-06-11T00:32:55.897474Z","iopub.status.idle":"2023-06-11T00:32:55.910092Z","shell.execute_reply.started":"2023-06-11T00:32:55.897436Z","shell.execute_reply":"2023-06-11T00:32:55.909137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ndatagen =  ImageDataGenerator(\n        zoom_range=0.6,  # set range for random zoom, changed from 0.15 to 0.3, now changed from 0.3 to 0.45, from 0.45 to 0.6\n        # set mode for filling points outside the input boundaries\n        fill_mode='constant',\n        cval=0.,  # value used for fill_mode = \"constant\"\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=True,# randomly flip images\n        rotation_range=360,\n        width_shift_range=0.1,\n        height_shift_range=0.1,\n        rescale=1./255\n    )","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:32:57.904633Z","iopub.execute_input":"2023-06-11T00:32:57.905683Z","iopub.status.idle":"2023-06-11T00:32:57.912938Z","shell.execute_reply.started":"2023-06-11T00:32:57.905638Z","shell.execute_reply":"2023-06-11T00:32:57.911545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import cohen_kappa_score, accuracy_score\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:01.180478Z","iopub.execute_input":"2023-06-11T00:33:01.181054Z","iopub.status.idle":"2023-06-11T00:33:02.239570Z","shell.execute_reply.started":"2023-06-11T00:33:01.181004Z","shell.execute_reply":"2023-06-11T00:33:02.238339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"true_labels = np.array([1, 0, 1, 1, 0, 1])\npred_labels = np.array([1, 0, 0, 0, 0, 1])","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:04.438524Z","iopub.execute_input":"2023-06-11T00:33:04.439059Z","iopub.status.idle":"2023-06-11T00:33:04.446107Z","shell.execute_reply.started":"2023-06-11T00:33:04.439019Z","shell.execute_reply":"2023-06-11T00:33:04.444700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy_score(true_labels, pred_labels)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:06.128524Z","iopub.execute_input":"2023-06-11T00:33:06.128984Z","iopub.status.idle":"2023-06-11T00:33:06.139184Z","shell.execute_reply.started":"2023-06-11T00:33:06.128945Z","shell.execute_reply":"2023-06-11T00:33:06.137938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cohen_kappa_score(true_labels, pred_labels)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:08.200775Z","iopub.execute_input":"2023-06-11T00:33:08.201286Z","iopub.status.idle":"2023-06-11T00:33:08.215719Z","shell.execute_reply.started":"2023-06-11T00:33:08.201241Z","shell.execute_reply":"2023-06-11T00:33:08.214240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import Callback\n\nclass Metrics(Callback):\n    def on_train_begin(self, logs={}):\n        self.val_kappas = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_val = y_val.sum(axis=1) - 1\n        y_pred = self.model.predict(X_val) > 0.5\n        y_pred = y_pred.astype(int).sum(axis=1) - 1\n        _val_kappa = cohen_kappa_score(\n        y_val,\n        y_pred, \n        weights='quadratic')\n        \n        \n\n        self.val_kappas.append(_val_kappa)\n\n        print(f\"val_kappa: {_val_kappa:.4f}\")\n\n        if _val_kappa == max(self.val_kappas):\n            print(\"Validation Kappa has improved. Saving model.\")\n            model.save_weights('model.h5')\n            model_json = model.to_json()\n            with open('model.json', \"w\") as json_file:\n                \n                json_file.write(model_json)\n                json_file.close()\n\n        return","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:10.136843Z","iopub.execute_input":"2023-06-11T00:33:10.137324Z","iopub.status.idle":"2023-06-11T00:33:10.150527Z","shell.execute_reply.started":"2023-06-11T00:33:10.137283Z","shell.execute_reply":"2023-06-11T00:33:10.149168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(images)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:16.277135Z","iopub.execute_input":"2023-06-11T00:33:16.277575Z","iopub.status.idle":"2023-06-11T00:33:16.286937Z","shell.execute_reply.started":"2023-06-11T00:33:16.277540Z","shell.execute_reply":"2023-06-11T00:33:16.285276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor i in label_arr:\n  if i == '4':\n    count = count+1\nprint(\"no of Proliferative DR[4]: \",count)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:18.488191Z","iopub.execute_input":"2023-06-11T00:33:18.488646Z","iopub.status.idle":"2023-06-11T00:33:18.498628Z","shell.execute_reply.started":"2023-06-11T00:33:18.488610Z","shell.execute_reply":"2023-06-11T00:33:18.497200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor i in label_arr:\n  if i == '3':\n    count = count+1\nprint(\"no of Severe[3]: \",count)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:20.372525Z","iopub.execute_input":"2023-06-11T00:33:20.372971Z","iopub.status.idle":"2023-06-11T00:33:20.381782Z","shell.execute_reply.started":"2023-06-11T00:33:20.372922Z","shell.execute_reply":"2023-06-11T00:33:20.380424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor i in label_arr:\n  if i == '2':\n    count = count+1\nprint(\"no of Moderate[2]: \",count)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:22.341023Z","iopub.execute_input":"2023-06-11T00:33:22.341704Z","iopub.status.idle":"2023-06-11T00:33:22.352191Z","shell.execute_reply.started":"2023-06-11T00:33:22.341654Z","shell.execute_reply":"2023-06-11T00:33:22.350431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor i in label_arr:\n  if i == '1':\n    count = count+1\nprint(\"no of Mild[1]: \",count)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:24.344947Z","iopub.execute_input":"2023-06-11T00:33:24.345455Z","iopub.status.idle":"2023-06-11T00:33:24.355954Z","shell.execute_reply.started":"2023-06-11T00:33:24.345411Z","shell.execute_reply":"2023-06-11T00:33:24.354387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor i in label_arr:\n  if i == '0':\n    count = count+1\nprint(\"no of healthy eyes: \",count)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:26.409125Z","iopub.execute_input":"2023-06-11T00:33:26.409541Z","iopub.status.idle":"2023-06-11T00:33:26.420403Z","shell.execute_reply.started":"2023-06-11T00:33:26.409508Z","shell.execute_reply":"2023-06-11T00:33:26.418851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_labels_ = list(set(train_Data['diagnosis'])) \nprint(\"Number of target classes: {}\".format(class_labels_))","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:30.936232Z","iopub.execute_input":"2023-06-11T00:33:30.936649Z","iopub.status.idle":"2023-06-11T00:33:30.944211Z","shell.execute_reply.started":"2023-06-11T00:33:30.936615Z","shell.execute_reply":"2023-06-11T00:33:30.942792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_labels = {0: 'No DR[0]',1: 'Mild[1]', 2: 'Moderate[2]', 3: 'Severe[3]', 4: 'Proliferative DR[4]'}\nclass_sizes = []\nfor i in range(0,5):\n    class_sizes.append(list(train_Data['diagnosis']).count(i))\nlabels = class_labels.values()\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','darkgreen']\nplt.pie(class_sizes,explode = [0.1,0,0,0,0], labels= labels, shadow = True,autopct='%1.1f%%', startangle = 35)\nplt.title('Pie Chart Analysis of Number of Images on each target label:')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:40.101842Z","iopub.execute_input":"2023-06-11T00:33:40.102300Z","iopub.status.idle":"2023-06-11T00:33:40.307523Z","shell.execute_reply.started":"2023-06-11T00:33:40.102262Z","shell.execute_reply":"2023-06-11T00:33:40.306028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(images,label_arr,stratify=label_arr,test_size=0.20,random_state=44)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:43.612911Z","iopub.execute_input":"2023-06-11T00:33:43.613327Z","iopub.status.idle":"2023-06-11T00:33:44.784762Z","shell.execute_reply.started":"2023-06-11T00:33:43.613294Z","shell.execute_reply":"2023-06-11T00:33:44.783264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train= np_utils.to_categorical(y_train, num_classes=5)\ny_test = np_utils.to_categorical(y_test, num_classes=5)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:47.996459Z","iopub.execute_input":"2023-06-11T00:33:47.996936Z","iopub.status.idle":"2023-06-11T00:33:48.005093Z","shell.execute_reply.started":"2023-06-11T00:33:47.996893Z","shell.execute_reply":"2023-06-11T00:33:48.004038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Conv2D(filters=16,kernel_size=2,padding=\"same\",activation=\"relu\",input_shape=(256,256,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(Conv2D(filters=128,kernel_size=2,padding=\"same\",activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(512,activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(5,activation=\"sigmoid\"))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:50.364640Z","iopub.execute_input":"2023-06-11T00:33:50.365399Z","iopub.status.idle":"2023-06-11T00:33:50.765363Z","shell.execute_reply.started":"2023-06-11T00:33:50.365351Z","shell.execute_reply":"2023-06-11T00:33:50.764156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow\n# from keras.callbacks import EarlyStopping\n# early_stop = EarlyStopping(monitor='val_loss', patience=3) callbacks=[early_stop]\nmodel.compile(loss='categorical_crossentropy',\n              optimizer='adam', metrics=['accuracy'])\nhist = model.fit(x_train,y_train,validation_split=0.10,batch_size=32,epochs=50,verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T00:33:55.408941Z","iopub.execute_input":"2023-06-11T00:33:55.409370Z","iopub.status.idle":"2023-06-11T01:03:18.437510Z","shell.execute_reply.started":"2023-06-11T00:33:55.409334Z","shell.execute_reply":"2023-06-11T01:03:18.436101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = model.predict(x_test)\n\nmodel.evaluate(x_test,y_test)\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:04:06.857850Z","iopub.execute_input":"2023-06-11T01:04:06.858325Z","iopub.status.idle":"2023-06-11T01:04:12.821273Z","shell.execute_reply.started":"2023-06-11T01:04:06.858286Z","shell.execute_reply":"2023-06-11T01:04:12.820381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, classification_report,confusion_matrix\nscore = round(accuracy_score(y_test.argmax(axis=1), pred.argmax(axis=1)),2)\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:04:20.377216Z","iopub.execute_input":"2023-06-11T01:04:20.377645Z","iopub.status.idle":"2023-06-11T01:04:20.386828Z","shell.execute_reply.started":"2023-06-11T01:04:20.377610Z","shell.execute_reply":"2023-06-11T01:04:20.385317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"report = classification_report(y_test.argmax(axis=1), pred.argmax(axis=1))\nprint(report)","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:04:26.937320Z","iopub.execute_input":"2023-06-11T01:04:26.937772Z","iopub.status.idle":"2023-06-11T01:04:26.951947Z","shell.execute_reply.started":"2023-06-11T01:04:26.937733Z","shell.execute_reply":"2023-06-11T01:04:26.950785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = hist.history['accuracy']\nloss = hist.history['loss']\n\nplt.figure(figsize = (8,8))\nplt.subplot(1,2,1)\nplt.plot(range(50),acc,label='Training Accuracy')\nplt.legend(loc=\"lower right\")\nplt.title(\"Training over 50 epochs\")\n","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:04:29.304979Z","iopub.execute_input":"2023-06-11T01:04:29.305427Z","iopub.status.idle":"2023-06-11T01:04:29.561706Z","shell.execute_reply.started":"2023-06-11T01:04:29.305381Z","shell.execute_reply":"2023-06-11T01:04:29.560129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (8,8))\nplt.subplot(1,2,1)\nplt.plot(range(50),loss,label='Training Loss')\nplt.legend(loc=\"upper right\")\nplt.title(\"Training Loss over 50 epochs\")","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:04:49.214084Z","iopub.execute_input":"2023-06-11T01:04:49.214549Z","iopub.status.idle":"2023-06-11T01:04:49.387173Z","shell.execute_reply.started":"2023-06-11T01:04:49.214514Z","shell.execute_reply":"2023-06-11T01:04:49.385929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('/kaggle/working/model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-06-11T01:35:34.565864Z","iopub.execute_input":"2023-06-11T01:35:34.566373Z","iopub.status.idle":"2023-06-11T01:35:35.409396Z","shell.execute_reply.started":"2023-06-11T01:35:34.566333Z","shell.execute_reply":"2023-06-11T01:35:35.408284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights('model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-06-11T02:09:48.716691Z","iopub.execute_input":"2023-06-11T02:09:48.717203Z","iopub.status.idle":"2023-06-11T02:09:48.807364Z","shell.execute_reply.started":"2023-06-11T02:09:48.717162Z","shell.execute_reply":"2023-06-11T02:09:48.806103Z"},"trusted":true},"execution_count":null,"outputs":[]}]}