{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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"},"colab":{"provenance":[],"authorship_tag":"ABX9TyOhg8D6UfcAFuyobec7BLOc"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":10835191,"sourceType":"datasetVersion","datasetId":6061872}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **Notebook for StitchingNet benchmark**\n- Hyungjung Kim revises this notebook from the original Python code composed by Jingu Kang.","metadata":{}},{"cell_type":"markdown","source":"## **1. First stage: Wide-screening**","metadata":{"id":"WOA8VVqiwO_o"}},{"cell_type":"markdown","source":"### Configuration","metadata":{"id":"tCvk60mJwZHa"}},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_hub as hub\nimport numpy as np\nimport pandas as pd\nimport glob\nimport time\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_score, recall_score, f1_score","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:22:54.031512Z","iopub.execute_input":"2026-02-16T09:22:54.032428Z","iopub.status.idle":"2026-02-16T09:22:54.037437Z","shell.execute_reply.started":"2026-02-16T09:22:54.032395Z","shell.execute_reply":"2026-02-16T09:22:54.036584Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 1-1. Data preprocessing with augmentation","metadata":{}},{"cell_type":"code","source":"def create_dataframe(filepath):\n labels = [str(filepath[i]).split(\"/\")[-2] for i in range(len(filepath))]\n filepath = pd.Series(filepath, name='Filepath').astype(str)\n labels = pd.Series(labels, name='Label')\n df = pd.concat([filepath, labels], axis=1)\n # Reset index\n df = df.sample(frac=1, random_state=0).reset_index(drop=True)\n \n return df\n\ndef create_data_generators(img_dir, data_batch_size):\n '''\n img_dir : StitchingNet image path(Format: ././*/*/*.jpg)\n batch_size : Set the data batch size\n '''\n \n # Search the img_dir\n image_paths = glob.glob(img_dir)\n\n # Save dataframes\n df = create_dataframe(image_paths)\n\n # Split train, valid, and test as 6:2:2 ratio\n train_df, test_df = train_test_split(df, test_size=0.2, random_state=0)\n # train_df.shape, test_df.shape\n \n train_df, valid_df = train_test_split(train_df, test_size=0.25, random_state=0)\n # train_df.shape, valid_df.shape\n\n\n # ImageDataGenerator for image augmentation\n train_datagen = ImageDataGenerator(rescale = 1./255,\n # rotation_range=30, # 회전제한 각도 30도\n # zoom_range=0.15, # 확대 축소 15%\n # width_shift_range=0.2, # 좌우이동 20%\n # height_shift_range=0.2, # 상하이동 20%\n # shear_range=0.15, # 반시계방햐의 각도\n # horizontal_flip=True, # 좌우 반전 True\n fill_mode=\"nearest\")\n valid_datagen = ImageDataGenerator(rescale = 1./255,\n # rotation_range=30, # 회전제한 각도 30도\n # zoom_range=0.15, # 확대 축소 15%\n # width_shift_range=0.2, # 좌우이동 20%\n # height_shift_range=0.2, # 상하이동 20%\n # shear_range=0.15, # 반시계방햐의 각도\n # horizontal_flip=True, # 좌우 반전 True\n fill_mode=\"nearest\")\n\n train_generator = train_datagen.flow_from_dataframe(train_df,\n x_col='Filepath',\n y_col='Label',\n target_size=(224, 224),\n batch_size=data_batch_size,\n class_mode='categorical'\n )\n validation_generator = valid_datagen.flow_from_dataframe(valid_df,\n x_col='Filepath',\n y_col='Label',\n target_size=(224, 224),\n batch_size=data_batch_size,\n class_mode='categorical'\n )\n # Test set으로 성능 확인\n test_datagen = ImageDataGenerator(rescale=1. / 255)\n test_generator = test_datagen.flow_from_dataframe(test_df,\n x_col='Filepath',\n y_col='Label',\n target_size=(224, 224),\n batch_size=data_batch_size\n )\n\n return train_generator, validation_generator, test_generator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:22:54.039060Z","iopub.execute_input":"2026-02-16T09:22:54.039370Z","iopub.status.idle":"2026-02-16T09:22:54.059163Z","shell.execute_reply.started":"2026-02-16T09:22:54.039347Z","shell.execute_reply":"2026-02-16T09:22:54.058485Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_dir = \"/kaggle/input/stitchingnet-dataset/*/*/*.jpg\"\ntrain, valid, test = create_data_generators(img_dir, 16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:22:54.059971Z","iopub.execute_input":"2026-02-16T09:22:54.060273Z","iopub.status.idle":"2026-02-16T09:23:13.132324Z","shell.execute_reply.started":"2026-02-16T09:22:54.060247Z","shell.execute_reply":"2026-02-16T09:23:13.131508Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 1-2. Model building","metadata":{}},{"cell_type":"code","source":"def build_model(model_name, trainable=False, num_classes=11):\n '''\n model_name: Model name to use\n trainable: Fine-tuning condition; False fixed\n num_classes: Number of classes; 11 fixed\n '''\n \n cnn_models = ['VGG19','DenseNet121','DenseNet169','DenseNet201','EfficientNetB0','EfficientNetB1','EfficientNetB7','EfficientNetV2B0','EfficientNetV2B3','EfficientNetV2L','EfficientNetV2M','EfficientNetV2S','InceptionV3','MobileNet','MobileNetV2','MobileNetV3Large','MobileNetV3Small','ResNet101','ResNet101V2','ResNet152','ResNet152V2','ResNet50','ResNet50V2','Xception']\n\n # For CNN models\n if model_name in cnn_models:\n\n # Model initilization, based on ImangeNet\n m_layer = getattr(tf.keras.applications, model_name)(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n m_layer.trainable = trainable\n\n x = m_layer.output\n x = tf.keras.layers.Flatten()(x)\n x = tf.keras.layers.Dense(1024, activation='relu')(x) # Add a dense layer\n output_layer = tf.keras.layers.Dense(11, activation='softmax')(x)\n\n model = tf.keras.models.Model(inputs = m_layer.input, outputs = output_layer)\n\n # For Vit models\n else:\n m_name = model_name.lower()\n vit_url = f\"https://www.kaggle.com/models/spsayakpaul/vision-transformer/TensorFlow2/{m_name}/1\"\n \n fe_layer = hub.KerasLayer(vit_url, trainable=trainable)\n \n inputs = tf.keras.Input(shape=(224,224,3))\n fe_output = fe_layer(inputs)\n x = tf.keras.layers.Dense(1024, activation='relu')(fe_output)\n outputs = tf.keras.layers.Dense(num_classes, activation='softmax')(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs, name=model_name)\n\n return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:23:13.134107Z","iopub.execute_input":"2026-02-16T09:23:13.134414Z","iopub.status.idle":"2026-02-16T09:23:13.141846Z","shell.execute_reply.started":"2026-02-16T09:23:13.134391Z","shell.execute_reply":"2026-02-16T09:23:13.141070Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 1-3. Model evaluation","metadata":{}},{"cell_type":"code","source":"def mode_evaluate(model,test):\n test_loss, test_accuracy = model.evaluate(test)\n\n all_pre = []\n all_label = []\n all_time = 0\n\n for i in range(len(test)):\n batch_x, batch_y = test[i]\n start_time = time.time()\n y_pred = model.predict(batch_x)\n end_time = time.time()\n y_pred_classes = np.argmax(y_pred, axis=1)\n y_label = np.argmax(batch_y, axis=1)\n\n all_pre.extend(y_pred_classes)\n all_label.extend(y_label)\n all_time += end_time - start_time\n\n # Calculate Precision, Recall, and F1-Score\n precision = precision_score(all_label, all_pre, average='weighted', zero_division=0)\n recall = recall_score(all_label, all_pre, average='weighted', zero_division=0)\n f1 = f1_score(all_label, all_pre, average='weighted', zero_division=0)\n # print(all_label, len(all_label))\n # print(all_pre, len(all_pre))\n # print(cnt)\n \n # Calculate Inference Time\n inference_time = all_time/len(test)\n\n return test_accuracy, test_loss, precision, recall, f1, inference_time","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:23:13.142750Z","iopub.execute_input":"2026-02-16T09:23:13.143042Z","iopub.status.idle":"2026-02-16T09:23:13.159601Z","shell.execute_reply.started":"2026-02-16T09:23:13.143013Z","shell.execute_reply":"2026-02-16T09:23:13.158958Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 1-4. Run benchmarks","metadata":{}},{"cell_type":"code","source":"# model_list = ['DenseNet121','DenseNet169','DenseNet201','EfficientNetB0','EfficientNetB1','EfficientNetB7','EfficientNetV2B0','EfficientNetV2B3','EfficientNetV2L','EfficientNetV2M','EfficientNetV2S','InceptionV3', 'MobileNet','MobileNetV2','MobileNetV3Large','MobileNetV3Small','ResNet101','ResNet101V2','ResNet152','ResNet152V2','ResNet50','ResNet50V2','Xception', 'vit-b16-fe','vit-r26-s32-medaug-fe', 'vit-r50-l32-fe','vit-b32-fe','vit-b8-fe', 'vit-l16-fe','vit-r26-s32-lightaug-fe','vit-s16-fe','VGG19']\n\nmodel_list = ['VGG19', 'ResNet50']\n\nmodel_result = []\n\nfor model_name in model_list:\n try:\n model = build_model(model_name)\n except:\n print(\"Failed to build %s\", model_name)\n continue\n\n # model.summary()\n\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n\n epochs = 100\n\n print(\"Model training started: \", model_name)\n \n model.fit(train, validation_data=valid, epochs=epochs, callbacks=[early_stopping])\n \n acc, test_loss, pre, rec, f1, inf_time = mode_evaluate(model, test)\n\n # Evaluation results\n print(f\"Test accuracy: {acc:.5f}\")\n print(f\"Test loss: {test_loss:.5f}\")\n print(f\"Precision: {pre:.5f}\")\n print(f\"Recall: {rec:.5f}\")\n print(f\"F1-score: {f1:.5f}\")\n print(f\"Inference time: {inf_time:.5f} seconds\")\n\n model_result.append([model_name, acc, pre, rec, f1, inf_time])\n\nresults_df = pd.DataFrame(model_result, columns=['Model','Accuracy','Precision','Recall','F1-score','Inference time'])\nresults_df.to_csv('./model_flatten_vgg19.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T09:23:13.160592Z","iopub.execute_input":"2026-02-16T09:23:13.160862Z","iopub.status.idle":"2026-02-16T09:45:05.651511Z","shell.execute_reply.started":"2026-02-16T09:23:13.160831Z","shell.execute_reply":"2026-02-16T09:45:05.650664Z"}},"outputs":[],"execution_count":null}]}