{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":39272,"databundleVersionId":4629629,"sourceType":"competition"},{"sourceId":2645886,"sourceType":"datasetVersion","datasetId":1608934},{"sourceId":4987732,"sourceType":"datasetVersion","datasetId":2892866},{"sourceId":9408599,"sourceType":"datasetVersion","datasetId":5712845}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"id":"b3fe4eb8-6892-4b07-8110-5f23cae97682","cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report,confusion_matrix\nimport numpy as np\nimport seaborn as sns\n\n\n","metadata":{"jupyter":{"is_executing":true},"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T11:03:01.007657Z","iopub.execute_input":"2025-08-20T11:03:01.008305Z","iopub.status.idle":"2025-08-20T11:03:01.011895Z","shell.execute_reply.started":"2025-08-20T11:03:01.008277Z","shell.execute_reply":"2025-08-20T11:03:01.011319Z"}},"outputs":[],"execution_count":null},{"id":"bbb131bf-4422-4c61-b66a-188f676240ed","cell_type":"code","source":"file_path='/kaggle/input/brain-tumor-mri-dataset/Testing'\ndatagen=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255,rotation_range=10,brightness_range=[0.8,1.2],zoom_range=0.15,validation_split=0.2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:48.625479Z","iopub.execute_input":"2025-08-20T10:36:48.625969Z","iopub.status.idle":"2025-08-20T10:36:48.716998Z","shell.execute_reply.started":"2025-08-20T10:36:48.625948Z","shell.execute_reply":"2025-08-20T10:36:48.716302Z"}},"outputs":[],"execution_count":null},{"id":"8663c583-58f8-4aa5-a5fe-6d9771189d2b","cell_type":"code","source":"train_data=datagen.flow_from_directory(file_path,target_size=(224,224),subset='training',batch_size=32,class_mode='categorical')\nval_data=datagen.flow_from_directory(file_path,target_size=(224,224),subset='validation',shuffle=False,batch_size=32,class_mode='categorical')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:48.717658Z","iopub.execute_input":"2025-08-20T10:36:48.717834Z","iopub.status.idle":"2025-08-20T10:36:49.392846Z","shell.execute_reply.started":"2025-08-20T10:36:48.71782Z","shell.execute_reply":"2025-08-20T10:36:49.392146Z"}},"outputs":[],"execution_count":null},{"id":"acd2b777-e3b4-46ab-b868-0ea1c4e807c9","cell_type":"code","source":"names=list(train_data.class_indices.keys())\nnames","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:49.394505Z","iopub.execute_input":"2025-08-20T10:36:49.39476Z","iopub.status.idle":"2025-08-20T10:36:49.399823Z","shell.execute_reply.started":"2025-08-20T10:36:49.394743Z","shell.execute_reply":"2025-08-20T10:36:49.399313Z"}},"outputs":[],"execution_count":null},{"id":"fb3b4d27-f895-4dd8-98aa-7f97f892aed8","cell_type":"code","source":"img,label = next(train_data)\nplt.figure(figsize=(20,20))\n\nfor i in range (4):  \n    plt.subplot(2,2,i+1)\n    plt.imshow(img[i])\n    plt.title(names[np.argmax(label[i])])\n    plt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:49.40041Z","iopub.execute_input":"2025-08-20T10:36:49.400954Z","iopub.status.idle":"2025-08-20T10:36:50.648983Z","shell.execute_reply.started":"2025-08-20T10:36:49.400936Z","shell.execute_reply":"2025-08-20T10:36:50.648245Z"}},"outputs":[],"execution_count":null},{"id":"e59e6585-3958-487d-a49d-f80f34e005d7","cell_type":"code","source":"class early_stopping(tf.keras.callbacks.Callback):\n    def __init__(self,threshold=0.5):\n        super(early_stopping,self).__init__()\n        self.threshold=threshold\n    def on_epoch_end(self,epoch,logs=None):\n        acc=logs.get('accuracy')\n        val=logs.get('val_accuracy')\n        if acc is not None and val is not None :\n            if acc>=self.threshold and val>=(self.threshold-0.04):\n                print(f'training stop at epochs {epoch+1}')\n                self.model.stop_training=True\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:50.649789Z","iopub.execute_input":"2025-08-20T10:36:50.650035Z","iopub.status.idle":"2025-08-20T10:36:50.656167Z","shell.execute_reply.started":"2025-08-20T10:36:50.650015Z","shell.execute_reply":"2025-08-20T10:36:50.655497Z"}},"outputs":[],"execution_count":null},{"id":"a398f1af-39fa-4c74-a09c-0ee7996e58d7","cell_type":"code","source":"early_stop=tf.keras.callbacks.EarlyStopping(patience=3,restore_best_weights=True,monitor='val_accuracy',mode='max',verbose=1)\nrlrp=tf.keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy',patience=3,mode='max',factor=0.3,min_lr=1e-6,verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:36:50.656887Z","iopub.execute_input":"2025-08-20T10:36:50.657086Z","iopub.status.idle":"2025-08-20T10:36:50.674467Z","shell.execute_reply.started":"2025-08-20T10:36:50.65707Z","shell.execute_reply":"2025-08-20T10:36:50.673968Z"}},"outputs":[],"execution_count":null},{"id":"7695c798-9092-4b3f-8814-91f23547bdad","cell_type":"code","source":"base=tf.keras.applications.ResNet50V2(include_top=False,weights='imagenet',input_shape=(224,224,3))\nfor layer in base.layers:\n    layer.trainable=False\nx=base.output\nx=tf.keras.layers.Conv2D(512,(3,3),padding='same',activation='relu')(x)\nx=tf.keras.layers.Conv2D(256,(3,3),padding='same',activation='relu')(x)\nx=tf.keras.layers.GlobalAveragePooling2D()(x)\nx=tf.keras.layers.Dropout(0.4)(x)\nx=tf.keras.layers.Dense(4,activation='softmax')(x)\nmodel=tf.keras.models.Model(inputs=base.input,outputs=x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:43:34.690902Z","iopub.execute_input":"2025-08-20T10:43:34.691233Z","iopub.status.idle":"2025-08-20T10:43:36.186733Z","shell.execute_reply.started":"2025-08-20T10:43:34.69121Z","shell.execute_reply":"2025-08-20T10:43:36.185914Z"}},"outputs":[],"execution_count":null},{"id":"cdba5f03-de7b-4b0f-93d4-46f4e3265191","cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),\n             loss=['categorical_crossentropy'],\n             metrics=['accuracy',tf.keras.metrics.Recall()],\n             )\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:43:37.905945Z","iopub.execute_input":"2025-08-20T10:43:37.906239Z","iopub.status.idle":"2025-08-20T10:43:38.066018Z","shell.execute_reply.started":"2025-08-20T10:43:37.906219Z","shell.execute_reply":"2025-08-20T10:43:38.065385Z"}},"outputs":[],"execution_count":null},{"id":"8043475a-c9c5-403f-9e25-0126dbc3d07c","cell_type":"code","source":"t_epochs=40\nmodel.fit(train_data,validation_data=val_data,epochs=t_epochs,callbacks=[early_stop,rlrp])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:43:43.976267Z","iopub.execute_input":"2025-08-20T10:43:43.976813Z","iopub.status.idle":"2025-08-20T10:48:01.385433Z","shell.execute_reply.started":"2025-08-20T10:43:43.976791Z","shell.execute_reply":"2025-08-20T10:48:01.384651Z"}},"outputs":[],"execution_count":null},{"id":"c978a6c2-a960-4694-8a62-763de7361dae","cell_type":"code","source":"path='/kaggle/input/brain-tumor-mri-dataset/Testing'\ntest=tf.keras.utils.image_dataset_from_directory(path,image_size=(224,224),shuffle=False,batch_size=16,label_mode='categorical')\nnorm=tf.keras.layers.Rescaling(1./255)\ntest=test.map(lambda x,y:(norm(x),y))\nmodel.evaluate(test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:50:30.382012Z","iopub.execute_input":"2025-08-20T10:50:30.382745Z","iopub.status.idle":"2025-08-20T10:50:45.005324Z","shell.execute_reply.started":"2025-08-20T10:50:30.38272Z","shell.execute_reply":"2025-08-20T10:50:45.004384Z"}},"outputs":[],"execution_count":null},{"id":"f3331e52-de5a-4bc7-ae37-6ca06d0e0682","cell_type":"code","source":"y_pred=np.argmax(model.predict(test),axis=1)\ny_true=np.concatenate([np.argmax(y,axis=1) for x,y in test],axis=0)\nclassification_report(y_true,y_pred,target_names=names)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T10:57:47.772067Z","iopub.execute_input":"2025-08-20T10:57:47.772949Z","iopub.status.idle":"2025-08-20T10:57:52.524697Z","shell.execute_reply.started":"2025-08-20T10:57:47.77292Z","shell.execute_reply":"2025-08-20T10:57:52.524052Z"}},"outputs":[],"execution_count":null},{"id":"1d876388-ddc8-4cb5-9308-66cf421c33e6","cell_type":"code","source":"cm = confusion_matrix(y_true, y_pred)\nsns.heatmap(cm, annot=True, fmt='d', xticklabels=names, yticklabels=names, cmap='pink')\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T11:03:58.758802Z","iopub.execute_input":"2025-08-20T11:03:58.759388Z","iopub.status.idle":"2025-08-20T11:03:58.963353Z","shell.execute_reply.started":"2025-08-20T11:03:58.759364Z","shell.execute_reply":"2025-08-20T11:03:58.962554Z"}},"outputs":[],"execution_count":null},{"id":"7406e995-771b-4dc6-90c0-a76b3886cb9e","cell_type":"code","source":"\nmodel.save('/kaggle/working/brain_tumor_modelv3.h5')\n\n\nprint(f\"Model saved successfully at {save_path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T11:11:11.571113Z","iopub.execute_input":"2025-08-20T11:11:11.571938Z","iopub.status.idle":"2025-08-20T11:11:12.280913Z","shell.execute_reply.started":"2025-08-20T11:11:11.571898Z","shell.execute_reply":"2025-08-20T11:11:12.280172Z"}},"outputs":[],"execution_count":null},{"id":"50ccedf6-9394-487f-834a-56b3099ad589","cell_type":"code","source":"from google.colab import files  \nfiles.download('/kaggle/working/brain_tumor_modelv3.h5')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-20T11:13:32.078571Z","iopub.execute_input":"2025-08-20T11:13:32.078966Z","iopub.status.idle":"2025-08-20T11:13:32.085835Z","shell.execute_reply.started":"2025-08-20T11:13:32.078935Z","shell.execute_reply":"2025-08-20T11:13:32.084983Z"}},"outputs":[],"execution_count":null},{"id":"6510731a-49c6-4e7d-949e-085c02236e26","cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}