{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":129474,"databundleVersionId":15526883,"isSourceIdPinned":false}],"dockerImageVersionId":31287,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:55:27.234583Z","iopub.execute_input":"2026-02-22T10:55:27.234945Z","iopub.status.idle":"2026-02-22T10:55:47.251001Z","shell.execute_reply.started":"2026-02-22T10:55:27.234911Z","shell.execute_reply":"2026-02-22T10:55:47.250232Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2 \nimport os\nimport pandas as pd \nimport numpy as np \nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,Dense,Flatten,Input,MaxPooling2D, Dropout,BatchNormalization, Reshape,GlobalAveragePooling2D\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:55:47.251925Z","iopub.execute_input":"2026-02-22T10:55:47.252294Z","iopub.status.idle":"2026-02-22T10:56:21.881827Z","shell.execute_reply.started":"2026-02-22T10:55:47.252270Z","shell.execute_reply":"2026-02-22T10:56:21.881251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels=[\"with_mask\",\"without_mask\"]\nimg_path=\"/kaggle/input/gdgoc-telkom-university-2026-mask-classification/Dataset/train/\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:21.883341Z","iopub.execute_input":"2026-02-22T10:56:21.883778Z","iopub.status.idle":"2026-02-22T10:56:21.887525Z","shell.execute_reply.started":"2026-02-22T10:56:21.883757Z","shell.execute_reply":"2026-02-22T10:56:21.886837Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_list=[]\nlabel_list=[]\nfor label in labels:\n    for img_file in os.listdir(img_path+label):\n        img_list.append(img_path+label+\"/\"+img_file)\n        label_list.append(label)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:21.888275Z","iopub.execute_input":"2026-02-22T10:56:21.889118Z","iopub.status.idle":"2026-02-22T10:56:21.935397Z","shell.execute_reply.started":"2026-02-22T10:56:21.889081Z","shell.execute_reply":"2026-02-22T10:56:21.934849Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df=pd.DataFrame({\"img\":img_list,\"label\":label_list})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:21.936153Z","iopub.execute_input":"2026-02-22T10:56:21.936396Z","iopub.status.idle":"2026-02-22T10:56:21.944322Z","shell.execute_reply.started":"2026-02-22T10:56:21.936367Z","shell.execute_reply":"2026-02-22T10:56:21.943717Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[\"img\"][0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:21.945162Z","iopub.execute_input":"2026-02-22T10:56:21.945441Z","iopub.status.idle":"2026-02-22T10:56:21.970313Z","shell.execute_reply.started":"2026-02-22T10:56:21.945413Z","shell.execute_reply":"2026-02-22T10:56:21.969738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:21.970959Z","iopub.execute_input":"2026-02-22T10:56:21.971237Z","iopub.status.idle":"2026-02-22T10:56:22.003683Z","shell.execute_reply.started":"2026-02-22T10:56:21.971218Z","shell.execute_reply":"2026-02-22T10:56:22.003158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"d={\"with_mask\":1,\"without_mask\":0}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:22.004356Z","iopub.execute_input":"2026-02-22T10:56:22.004584Z","iopub.status.idle":"2026-02-22T10:56:22.007935Z","shell.execute_reply.started":"2026-02-22T10:56:22.004556Z","shell.execute_reply":"2026-02-22T10:56:22.007363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['encode_label']=df['label'].map(d)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:22.011494Z","iopub.execute_input":"2026-02-22T10:56:22.011731Z","iopub.status.idle":"2026-02-22T10:56:22.026961Z","shell.execute_reply.started":"2026-02-22T10:56:22.011712Z","shell.execute_reply":"2026-02-22T10:56:22.026227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[\"label\"].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:22.027816Z","iopub.execute_input":"2026-02-22T10:56:22.028015Z","iopub.status.idle":"2026-02-22T10:56:22.051636Z","shell.execute_reply.started":"2026-02-22T10:56:22.027998Z","shell.execute_reply":"2026-02-22T10:56:22.050778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x=[] #bos liste\nfor img in df[\"img\"]:\n    img=cv2.imread(str(img))\n    img=cv2.resize(img,(170,170))\n    img=img/255.0 #normalize ediyoruz\n    x.append(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:56:22.052725Z","iopub.execute_input":"2026-02-22T10:56:22.052972Z","iopub.status.idle":"2026-02-22T10:57:42.267840Z","shell.execute_reply.started":"2026-02-22T10:56:22.052953Z","shell.execute_reply":"2026-02-22T10:57:42.267199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x=np.array(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:57:42.268865Z","iopub.execute_input":"2026-02-22T10:57:42.269150Z","iopub.status.idle":"2026-02-22T10:57:44.212166Z","shell.execute_reply.started":"2026-02-22T10:57:42.269115Z","shell.execute_reply":"2026-02-22T10:57:44.211578Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y=df['encode_label']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:57:44.213328Z","iopub.execute_input":"2026-02-22T10:57:44.213610Z","iopub.status.idle":"2026-02-22T10:57:44.217326Z","shell.execute_reply.started":"2026-02-22T10:57:44.213581Z","shell.execute_reply":"2026-02-22T10:57:44.216772Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=42,test_size=0.2,stratify=y)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:58:48.664582Z","iopub.execute_input":"2026-02-22T10:58:48.664850Z","iopub.status.idle":"2026-02-22T10:58:50.113149Z","shell.execute_reply.started":"2026-02-22T10:58:48.664829Z","shell.execute_reply":"2026-02-22T10:58:50.112556Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train=np.array(y_train, dtype=np.int32)\ny_test=np.array(y_test, dtype=np.int32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:58:50.114568Z","iopub.execute_input":"2026-02-22T10:58:50.114887Z","iopub.status.idle":"2026-02-22T10:58:50.119191Z","shell.execute_reply.started":"2026-02-22T10:58:50.114854Z","shell.execute_reply":"2026-02-22T10:58:50.118449Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential([\n    Input(shape=(170,170,3)),\n\n    Conv2D(32, 3, activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    Conv2D(64, 3, activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    Conv2D(128, 3, activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    GlobalAveragePooling2D(),\n\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n\n    Dense(1, activation='sigmoid')\n])\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:58:50.120155Z","iopub.execute_input":"2026-02-22T10:58:50.120831Z","iopub.status.idle":"2026-02-22T10:58:54.046275Z","shell.execute_reply.started":"2026-02-22T10:58:50.120801Z","shell.execute_reply":"2026-02-22T10:58:54.045493Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:58:54.048186Z","iopub.execute_input":"2026-02-22T10:58:54.048432Z","iopub.status.idle":"2026-02-22T10:58:54.054834Z","shell.execute_reply.started":"2026-02-22T10:58:54.048411Z","shell.execute_reply":"2026-02-22T10:58:54.054047Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model.fit(x_train,y_train,validation_data=(x_test,y_test), epochs=20,verbose=1,callbacks=[early_stopping])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T10:58:54.055795Z","iopub.execute_input":"2026-02-22T10:58:54.056192Z","iopub.status.idle":"2026-02-22T11:01:11.960756Z","shell.execute_reply.started":"2026-02-22T10:58:54.056162Z","shell.execute_reply":"2026-02-22T11:01:11.960094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"Mask.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:01:11.962879Z","iopub.execute_input":"2026-02-22T11:01:11.963794Z","iopub.status.idle":"2026-02-22T11:01:12.028003Z","shell.execute_reply.started":"2026-02-22T11:01:11.963769Z","shell.execute_reply":"2026-02-22T11:01:12.027460Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import VGG16, ResNet50, MobileNetV2\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:01:12.028752Z","iopub.execute_input":"2026-02-22T11:01:12.028983Z","iopub.status.idle":"2026-02-22T11:01:12.036683Z","shell.execute_reply.started":"2026-02-22T11:01:12.028952Z","shell.execute_reply":"2026-02-22T11:01:12.036059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_dir=\"/kaggle/input/gdgoc-telkom-university-2026-mask-classification/Dataset/train\"\n\nimg_width,img_heigth=224,224\ntrain_datagen=ImageDataGenerator(rescale=1/255, validation_split=0.20)\ntrain_datagenerator=train_datagen.flow_from_directory(directory=data_dir,target_size=(img_width,img_heigth),\n                                class_mode='sparse', subset='training')\ntest_datagen=ImageDataGenerator(rescale=1/255)\ntest_datagenerator=train_datagen.flow_from_directory(directory=data_dir,target_size=(img_width,img_heigth),\n                                class_mode='sparse', subset='validation')\n\nbase_model=MobileNetV2(weights='imagenet', input_shape=(img_width,img_heigth,3), include_top=False)\nbase_model.trainable = False\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.5)(x)\noutputs = Dense(1, activation='sigmoid')(x)\n\nmodel = Model(inputs=base_model.input, outputs=outputs)\n\nmodel.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:01:12.037564Z","iopub.execute_input":"2026-02-22T11:01:12.037798Z","iopub.status.idle":"2026-02-22T11:01:19.258648Z","shell.execute_reply.started":"2026-02-22T11:01:12.037779Z","shell.execute_reply":"2026-02-22T11:01:19.258083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:01:19.259467Z","iopub.execute_input":"2026-02-22T11:01:19.259700Z","iopub.status.idle":"2026-02-22T11:01:19.263255Z","shell.execute_reply.started":"2026-02-22T11:01:19.259671Z","shell.execute_reply":"2026-02-22T11:01:19.262589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.fit(train_datagenerator,epochs=10,validation_data=test_datagenerator,callbacks=[early_stopping])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:01:19.265465Z","iopub.execute_input":"2026-02-22T11:01:19.265797Z","iopub.status.idle":"2026-02-22T11:04:36.028240Z","shell.execute_reply.started":"2026-02-22T11:01:19.265770Z","shell.execute_reply":"2026-02-22T11:04:36.027593Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"Mask.TL.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:04:36.029210Z","iopub.execute_input":"2026-02-22T11:04:36.029499Z","iopub.status.idle":"2026-02-22T11:04:36.312214Z","shell.execute_reply.started":"2026-02-22T11:04:36.029468Z","shell.execute_reply":"2026-02-22T11:04:36.311342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"loss, accuracy=model.evaluate(test_datagenerator)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:04:36.313361Z","iopub.execute_input":"2026-02-22T11:04:36.313634Z","iopub.status.idle":"2026-02-22T11:04:41.880115Z","shell.execute_reply.started":"2026-02-22T11:04:36.313603Z","shell.execute_reply":"2026-02-22T11:04:41.879398Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TEST_DIR = \"/kaggle/input/gdgoc-telkom-university-2026-mask-classification/Dataset/test\"\nIMG_SIZE = (224, 224)\n\n\ndef pred_to_label(prob, thr=0.5):\n    return \"without_mask\" if prob >= thr else \"with_mask\"\n\ntest_files = sorted([\n    f for f in os.listdir(TEST_DIR)\n    if f.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".webp\"))\n])\n\nrows = []\nfor fname in test_files:\n    path = os.path.join(TEST_DIR, fname)\n\n    img = tf.keras.utils.load_img(path, target_size=IMG_SIZE)\n    x = tf.keras.utils.img_to_array(img) / 255.0   # rescale=1/255 ile aynı\n    x = np.expand_dims(x, axis=0)                  # (1,224,224,3)\n\n    prob = float(model.predict(x, verbose=0)[0][0])  # sigmoid probability\n    label = pred_to_label(prob, thr=0.5)\n\n    rows.append({\n        \"image\": fname,\n        \"label\": label,\n        \"prob_with_mask\": prob\n    })\n\npred_df = pd.DataFrame(rows)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:06:29.223390Z","iopub.execute_input":"2026-02-22T11:06:29.223675Z","iopub.status.idle":"2026-02-22T11:07:00.377624Z","shell.execute_reply.started":"2026-02-22T11:06:29.223654Z","shell.execute_reply":"2026-02-22T11:07:00.376931Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:07:00.378744Z","iopub.execute_input":"2026-02-22T11:07:00.378942Z","iopub.status.idle":"2026-02-22T11:07:00.386640Z","shell.execute_reply.started":"2026-02-22T11:07:00.378922Z","shell.execute_reply":"2026-02-22T11:07:00.386078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({'filename': pred_df['image'], 'label': pred_df[\"label\"]})\nsubmission.to_csv('submission.csv', index=False)\n\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T11:07:26.458227Z","iopub.execute_input":"2026-02-22T11:07:26.458513Z","iopub.status.idle":"2026-02-22T11:07:26.469633Z","shell.execute_reply.started":"2026-02-22T11:07:26.458493Z","shell.execute_reply":"2026-02-22T11:07:26.468901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}