{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":47453,"databundleVersionId":5136115,"sourceType":"competition"}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-12-28T12:01:09.242904Z","iopub.execute_input":"2023-12-28T12:01:09.243324Z","iopub.status.idle":"2023-12-28T12:01:13.176800Z","shell.execute_reply.started":"2023-12-28T12:01:09.243289Z","shell.execute_reply":"2023-12-28T12:01:13.175621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"neg_dataset = pd.read_csv('/kaggle/input/earthquake-road-crack-detection/neg_data.csv')\npos_dataset = pd.read_csv('/kaggle/input/earthquake-road-crack-detection/pos_data.csv')\nneg_dataset.describe().T","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:02:22.813488Z","iopub.execute_input":"2023-12-28T12:02:22.814795Z","iopub.status.idle":"2023-12-28T12:02:25.772159Z","shell.execute_reply.started":"2023-12-28T12:02:22.814739Z","shell.execute_reply":"2023-12-28T12:02:25.770946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport os\ndef read_and_resize_images(folder_path, target_size=(224, 224)):\n    images = []\n    labels = []\n\n    for filename in os.listdir(folder_path):\n        if filename.endswith(\".jpg\"):  # Assuming all images are in jpg format\n            img_path = os.path.join(folder_path, filename)\n            label = 1 if \"pos\" in folder_path else 0  # Assign label 1 for positive and 0 for negative\n\n            # Read and resize the image\n            img = cv2.imread(img_path)\n            img = cv2.resize(img, target_size)\n\n            images.append(img)\n            labels.append(label)\n\n    return images, labels\n\n# positive images\npos_folder_path = \"/kaggle/input/earthquake-road-crack-detection/Earthquake Road Crack Detection/Earthquake Road Crack Detection/pos\"\npos_images, pos_labels = read_and_resize_images(pos_folder_path)\n\n# negative images\nneg_folder_path = \"/kaggle/input/earthquake-road-crack-detection/Earthquake Road Crack Detection/Earthquake Road Crack Detection/neg\"\nneg_images, neg_labels = read_and_resize_images(neg_folder_path)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:02:32.574038Z","iopub.execute_input":"2023-12-28T12:02:32.574609Z","iopub.status.idle":"2023-12-28T12:04:14.345785Z","shell.execute_reply.started":"2023-12-28T12:02:32.574559Z","shell.execute_reply":"2023-12-28T12:04:14.344746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import imgaug.augmenters as iaa\nimport numpy as np\nimport cv2\nimport os\n\n# Function to perform data augmentation on images\ndef augment_images(images, labels, augmentation_factor=2):\n    augmented_images = []\n    augmented_labels = []\n\n    for image, label in zip(images, labels):\n        augmented_images.append(image)\n        augmented_labels.append(label)\n\n        # Apply augmentation_factor times augmentation to each image\n        for _ in range(augmentation_factor):\n            augmented_image = apply_augmentation(image)\n            augmented_images.append(augmented_image)\n            augmented_labels.append(label)\n\n    return augmented_images, augmented_labels\n\n# Function to apply augmentation to a single image\ndef apply_augmentation(image):\n    seq = iaa.Sequential([\n        iaa.Fliplr(0.2),   # 50% horizontal flip\n        iaa.Affine(rotate=(-5, 5)),  # Rotate between -10 and 10 degrees\n    ], random_order=True)\n\n    augmented_image = seq.augment_image(image)\n    return augmented_image\n\n# Assuming pos_images and pos_labels are your original positive images and labels\naugmented_pos_images, augmented_pos_labels = augment_images(pos_images, pos_labels)\n\n# Assuming neg_images and neg_labels are your original negative images and labels\naugmented_neg_images, augmented_neg_labels = augment_images(neg_images, neg_labels)\n\n# Combine original and augmented datasets\nall_images = np.concatenate([augmented_pos_images, augmented_neg_images])\nall_labels = np.concatenate([augmented_pos_labels, augmented_neg_labels])\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:05:22.933961Z","iopub.execute_input":"2023-12-28T12:05:22.934466Z","iopub.status.idle":"2023-12-28T12:05:51.923603Z","shell.execute_reply.started":"2023-12-28T12:05:22.934426Z","shell.execute_reply":"2023-12-28T12:05:51.922269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n# Assuming all_images is your combined dataset and all_labels is the corresponding labels\n# Adjust the test_size and random_state parameters as needed\n\n# Split the data into training and temporary sets\ntemp_images, test_images, temp_labels, test_labels = train_test_split(\n    all_images, all_labels, test_size=0.2, random_state=42\n)\n\n# Split the temporary set into training and validation sets\ntrain_images, val_images, train_labels, val_labels = train_test_split(\n    temp_images, temp_labels, test_size=0.2, random_state=42\n)\n\n# Print the sizes of the resulting sets\nprint(\"Training set:\", len(train_images), \"images\")\nprint(\"Validation set:\", len(val_images), \"images\")\nprint(\"Test set:\", len(test_images), \"images\")\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:08:35.280663Z","iopub.execute_input":"2023-12-28T12:08:35.281147Z","iopub.status.idle":"2023-12-28T12:08:37.271544Z","shell.execute_reply.started":"2023-12-28T12:08:35.281109Z","shell.execute_reply":"2023-12-28T12:08:37.270279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\n\n# Assuming input_shape is the shape of your images, e.g., (224, 224, 3)\ninput_shape = (224, 224, 3)\n\n# Create a simple CNN model\nmodel = models.Sequential()\n\n# Convolutional layers\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Flatten layer to transition from convolutional layers to dense layers\nmodel.add(layers.Flatten())\n\n# Dense layers\nmodel.add(layers.Dense(128, activation='relu'))\nmodel.add(layers.Dropout(0.5))  # Dropout for regularization\n\n# Output layer\nmodel.add(layers.Dense(1, activation='sigmoid'))  # Assuming binary classification (0 or 1)\n\n# Compile the model\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\n# Display the model summary\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:10:51.063622Z","iopub.execute_input":"2023-12-28T12:10:51.064199Z","iopub.status.idle":"2023-12-28T12:11:07.386051Z","shell.execute_reply.started":"2023-12-28T12:10:51.064149Z","shell.execute_reply":"2023-12-28T12:11:07.384308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming train_images, train_labels, val_images, val_labels are your training and validation sets\n\n# Train the model\nhistory = model.fit(\n    train_images, train_labels,\n    epochs=10,  # Adjust the number of epochs based on your needs\n    validation_data=(val_images, val_labels),\n    verbose=1\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T12:13:49.782765Z","iopub.execute_input":"2023-12-28T12:13:49.783240Z","iopub.status.idle":"2023-12-28T14:21:44.176325Z","shell.execute_reply.started":"2023-12-28T12:13:49.783202Z","shell.execute_reply":"2023-12-28T14:21:44.175224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming test_images, test_labels are your test set\n\n# Evaluate the model on the test set\ntest_loss, test_accuracy = model.evaluate(test_images, test_labels)\n\nprint(\"Test Loss:\", test_loss)\nprint(\"Test Accuracy:\", test_accuracy)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T14:22:03.665290Z","iopub.execute_input":"2023-12-28T14:22:03.665720Z","iopub.status.idle":"2023-12-28T14:23:27.240709Z","shell.execute_reply.started":"2023-12-28T14:22:03.665687Z","shell.execute_reply":"2023-12-28T14:23:27.239410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot training history\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-12-28T14:24:11.204965Z","iopub.execute_input":"2023-12-28T14:24:11.205489Z","iopub.status.idle":"2023-12-28T14:24:11.599579Z","shell.execute_reply.started":"2023-12-28T14:24:11.205450Z","shell.execute_reply":"2023-12-28T14:24:11.597758Z"},"trusted":true},"execution_count":null,"outputs":[]}]}