{"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-10T17:21:35.848798Z","iopub.execute_input":"2023-06-10T17:21:35.849146Z","iopub.status.idle":"2023-06-10T17:21:44.706494Z","shell.execute_reply.started":"2023-06-10T17:21:35.849118Z","shell.execute_reply":"2023-06-10T17:21:44.705548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import ResNet50\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, GlobalAveragePooling2D\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.model_selection import train_test_split\n","metadata":{"execution":{"iopub.status.busy":"2023-06-10T17:21:44.708637Z","iopub.execute_input":"2023-06-10T17:21:44.709271Z","iopub.status.idle":"2023-06-10T17:21:54.355190Z","shell.execute_reply.started":"2023-06-10T17:21:44.709239Z","shell.execute_reply":"2023-06-10T17:21:54.354102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load dataset\ntrain_df = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/train.csv')\ntest_df = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/test.csv')\n\n# Add '.png' extension to id_code\ntrain_df['id_code'] = train_df['id_code'].apply(lambda x: x + \".png\")\ntest_df['id_code'] = test_df['id_code'].apply(lambda x: x + \".png\")\n\n# Convert the labels to string\ntrain_df['diagnosis'] = train_df['diagnosis'].astype('str')\n","metadata":{"execution":{"iopub.status.busy":"2023-06-10T17:21:54.356764Z","iopub.execute_input":"2023-06-10T17:21:54.358018Z","iopub.status.idle":"2023-06-10T17:21:54.397889Z","shell.execute_reply.started":"2023-06-10T17:21:54.357980Z","shell.execute_reply":"2023-06-10T17:21:54.396992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# normalize the images\ntrain_df['diagnosis'] = train_df['diagnosis'].astype('str')\n\n# Split the data\ntrain_df, val_df = train_test_split(train_df, test_size=0.2)\n\n# Generate batches of tensor image data for train and validation\ndatagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory='/kaggle/input/aptos2019-blindness-detection/train_images/',\n    x_col='id_code',\n    y_col='diagnosis',\n    batch_size=32,\n    class_mode='categorical',\n    target_size=(224, 224))\n\nval_generator = datagen.flow_from_dataframe(\n    dataframe=val_df,\n    directory='/kaggle/input/aptos2019-blindness-detection/train_images/',\n    x_col='id_code',\n    y_col='diagnosis',\n    batch_size=32,\n    class_mode='categorical',\n    target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2023-06-10T17:21:54.400526Z","iopub.execute_input":"2023-06-10T17:21:54.400931Z","iopub.status.idle":"2023-06-10T17:21:55.874878Z","shell.execute_reply.started":"2023-06-10T17:21:54.400899Z","shell.execute_reply":"2023-06-10T17:21:55.873918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the ResNet50 base model\nbase_model = ResNet50(include_top=False, pooling='avg')\n\n# Make the base model untrainable\nbase_model.trainable = False\n\n# Define the model\nmodel = Sequential([\n    base_model,\n    Dense(5, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-06-10T17:21:55.876247Z","iopub.execute_input":"2023-06-10T17:21:55.876710Z","iopub.status.idle":"2023-06-10T17:22:03.990982Z","shell.execute_reply.started":"2023-06-10T17:21:55.876674Z","shell.execute_reply":"2023-06-10T17:22:03.989940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the callbacks\ncallbacks = [EarlyStopping(patience=3, restore_best_weights=True),\n             ModelCheckpoint(filepath='model.h5', save_best_only=True)]\n\n# Train the model\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch = train_generator.n//train_generator.batch_size,\n    validation_data = val_generator, \n    validation_steps = val_generator.n//val_generator.batch_size,\n    epochs = 10,\n    callbacks=callbacks)","metadata":{"execution":{"iopub.status.busy":"2023-06-10T17:22:03.992478Z","iopub.execute_input":"2023-06-10T17:22:03.992878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, accuracy = model.evaluate(val_generator)\nprint(f'Loss: {loss}')\nprint(f'Accuracy: {accuracy}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\n\n# Plot training & validation loss values\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}