{"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":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout, BatchNormalization\nfrom tensorflow.keras.models import Model, load_model, Sequential\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom tensorflow.keras.optimizers import Adam, Adamax\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.metrics import categorical_crossentropy\nimport matplotlib.pyplot as plt\nimport numpy as np\n","metadata":{"execution":{"iopub.status.busy":"2023-05-12T12:57:37.928670Z","iopub.execute_input":"2023-05-12T12:57:37.929084Z","iopub.status.idle":"2023-05-12T12:57:45.992900Z","shell.execute_reply.started":"2023-05-12T12:57:37.929025Z","shell.execute_reply":"2023-05-12T12:57:45.991715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocessing the Training set\ntrain_datagen = ImageDataGenerator(  rescale=1./255)\n                                   #zoom_range=0.2,horizontal_flip=True)\n\ntrain_data = train_datagen.flow_from_directory(\"/kaggle/input/apple13/NewApple1/train\",\n                                              target_size=(224,224),\n                                              batch_size=64,\n                                              class_mode='categorical',seed=42,\n                                              subset = 'training')\n\nval_data = train_datagen.flow_from_directory(\"/kaggle/input/apple13/NewApple1/val\",\n                                            target_size=(224,224),\n                                            batch_size=64,\n                                            class_mode='categorical',seed=42)\ntest_data = train_datagen.flow_from_directory('/kaggle/input/apple13/NewApple1/test',\n                                            target_size=(224,224),\n                                            batch_size=64,\n                                            class_mode='categorical',seed=42,shuffle=False)\nprint(train_data.class_indices)","metadata":{"execution":{"iopub.status.busy":"2023-05-12T12:57:52.092508Z","iopub.execute_input":"2023-05-12T12:57:52.093943Z","iopub.status.idle":"2023-05-12T12:57:58.669143Z","shell.execute_reply.started":"2023-05-12T12:57:52.093893Z","shell.execute_reply":"2023-05-12T12:57:58.667939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xcep=tf.keras.applications.MobileNetV2(input_shape=(224,224,3),weights='imagenet', include_top=False)\nfor i in xcep.layers:\n    i.trainable = False\n\nmodel=keras.models.Sequential()\nmodel.add(xcep)\nmodel.add(keras.layers.Flatten())\nmodel.add(keras.layers.Dense(300, activation=\"relu\"))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Dense(100,activation='relu'))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Dense(6,activation=\"sigmoid\"))\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-05-12T12:57:58.671611Z","iopub.execute_input":"2023-05-12T12:57:58.672362Z","iopub.status.idle":"2023-05-12T12:58:04.239173Z","shell.execute_reply.started":"2023-05-12T12:57:58.672318Z","shell.execute_reply":"2023-05-12T12:58:04.238111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='SGD',loss='categorical_crossentropy',metrics=['accuracy'])\ncallback2 = tf.keras.callbacks.EarlyStopping(monitor = 'accuracy', patience = 3, restore_best_weights = True)","metadata":{"execution":{"iopub.status.busy":"2023-05-12T12:58:04.240645Z","iopub.execute_input":"2023-05-12T12:58:04.241054Z","iopub.status.idle":"2023-05-12T12:58:04.266539Z","shell.execute_reply.started":"2023-05-12T12:58:04.240993Z","shell.execute_reply":"2023-05-12T12:58:04.265603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_data,steps_per_epoch=12091//64,epochs=10,validation_data=val_data,validation_steps=1726//64,callbacks=[callback2])","metadata":{"execution":{"iopub.status.busy":"2023-05-12T12:58:04.268627Z","iopub.execute_input":"2023-05-12T12:58:04.269300Z","iopub.status.idle":"2023-05-12T18:46:40.253626Z","shell.execute_reply.started":"2023-05-12T12:58:04.269260Z","shell.execute_reply":"2023-05-12T18:46:40.250866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc_train=history.history['accuracy']\nacc_val=history.history['val_accuracy']\nepochs=range(len(acc_train))\nplt.figure(figsize=(8,8))\nplt.plot(epochs,acc_train,'g',label='Training Accuracy')\nplt.plot(epochs,acc_val,'b',label='Validation Accuracy')\nplt.title(\"Training and Validation Accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-12T18:49:34.392579Z","iopub.execute_input":"2023-05-12T18:49:34.393068Z","iopub.status.idle":"2023-05-12T18:49:34.798571Z","shell.execute_reply.started":"2023-05-12T18:49:34.393010Z","shell.execute_reply":"2023-05-12T18:49:34.797348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_train=history.history['loss']\nloss_val=history.history['val_loss']\nepochs=range(len(loss_train))\nplt.figure(figsize=(12,12))\nplt.plot(epochs,loss_train,'g',label='Training Loss')\nplt.plot(epochs,loss_val,'b',label='Validation Loss')\nplt.title(\"Training and Validation Loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-12T18:49:37.155205Z","iopub.execute_input":"2023-05-12T18:49:37.155647Z","iopub.status.idle":"2023-05-12T18:49:37.527174Z","shell.execute_reply.started":"2023-05-12T18:49:37.155605Z","shell.execute_reply":"2023-05-12T18:49:37.526119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_accuracy =model.evaluate(test_data,batch_size=64)[1] * 100\nprint('Test accuracy is : ',test_accuracy, '%' )","metadata":{"execution":{"iopub.status.busy":"2023-05-12T18:49:48.331390Z","iopub.execute_input":"2023-05-12T18:49:48.332470Z","iopub.status.idle":"2023-05-12T18:58:32.930580Z","shell.execute_reply.started":"2023-05-12T18:49:48.332408Z","shell.execute_reply":"2023-05-12T18:58:32.929514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"true_classes = test_data.classes\nclass_labels = list(test_data.class_indices.keys())","metadata":{"execution":{"iopub.status.busy":"2023-05-12T18:58:32.932948Z","iopub.execute_input":"2023-05-12T18:58:32.933441Z","iopub.status.idle":"2023-05-12T18:58:32.941761Z","shell.execute_reply.started":"2023-05-12T18:58:32.933397Z","shell.execute_reply":"2023-05-12T18:58:32.940630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_steps_per_epoch = np.math.ceil(test_data.samples / test_data.batch_size)\n\npredictions = model.predict(test_data, steps = test_steps_per_epoch)\n\npredicted_classes = np.argmax(predictions, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-05-12T18:58:32.943147Z","iopub.execute_input":"2023-05-12T18:58:32.944013Z","iopub.status.idle":"2023-05-12T19:06:57.201724Z","shell.execute_reply.started":"2023-05-12T18:58:32.943969Z","shell.execute_reply":"2023-05-12T19:06:57.200612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sklearn \nreport = sklearn.metrics.classification_report(true_classes, predicted_classes, target_names = class_labels)\nprint(report)","metadata":{"execution":{"iopub.status.busy":"2023-05-12T19:06:57.204651Z","iopub.execute_input":"2023-05-12T19:06:57.204969Z","iopub.status.idle":"2023-05-12T19:06:57.221433Z","shell.execute_reply.started":"2023-05-12T19:06:57.204937Z","shell.execute_reply":"2023-05-12T19:06:57.220379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nimport sklearn.metrics as metrics\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay  \ncm = sklearn.metrics.confusion_matrix(true_classes, predicted_classes)\nplt.figure(figsize=(7,7))\nsns.heatmap(cm, fmt='.0f', cmap=\"crest\", annot=True, linewidths=0.2, xticklabels=class_labels, yticklabels=class_labels)\nplt.title('confusion matrix')\nplt.xlabel('predicted classes')\nplt.ylabel('True classes')\nplt.show()\nprint(sklearn.metrics.confusion_matrix(true_classes, predicted_classes))","metadata":{"execution":{"iopub.status.busy":"2023-05-12T19:20:25.310126Z","iopub.execute_input":"2023-05-12T19:20:25.310880Z","iopub.status.idle":"2023-05-12T19:20:26.088246Z","shell.execute_reply.started":"2023-05-12T19:20:25.310839Z","shell.execute_reply":"2023-05-12T19:20:26.087114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_accuracy = model.evaluate(train_data,batch_size=64)[1] * 100\nprint('Train accuracy is : ',train_accuracy, '%' )","metadata":{"execution":{"iopub.status.busy":"2023-05-12T19:20:28.478536Z","iopub.execute_input":"2023-05-12T19:20:28.478934Z","iopub.status.idle":"2023-05-12T19:51:00.405064Z","shell.execute_reply.started":"2023-05-12T19:20:28.478899Z","shell.execute_reply":"2023-05-12T19:51:00.403005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_accuracy = model.evaluate(val_data,batch_size=64)[1] * 100\nprint('val accuracy is : ',val_accuracy, '%' )","metadata":{"execution":{"iopub.status.busy":"2023-05-12T19:51:00.407551Z","iopub.execute_input":"2023-05-12T19:51:00.408837Z","iopub.status.idle":"2023-05-12T19:55:32.503487Z","shell.execute_reply.started":"2023-05-12T19:51:00.408798Z","shell.execute_reply":"2023-05-12T19:55:32.502369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import scikitplot as skplt\n\ny_true = true_classes\ny_probas = predictions\nskplt.metrics.plot_roc_curve(y_true, y_probas)\nplt.figure(figsize=(12,12))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-12T19:55:32.507009Z","iopub.execute_input":"2023-05-12T19:55:32.507353Z","iopub.status.idle":"2023-05-12T19:55:33.076485Z","shell.execute_reply.started":"2023-05-12T19:55:32.507321Z","shell.execute_reply":"2023-05-12T19:55:33.075432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}