{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport cv2\nimport os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.datasets import load_files\nimport tensorflow as tf\nimport random","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-11T17:55:52.171641Z","iopub.execute_input":"2024-10-11T17:55:52.172345Z","iopub.status.idle":"2024-10-11T17:56:05.957094Z","shell.execute_reply.started":"2024-10-11T17:55:52.172303Z","shell.execute_reply":"2024-10-11T17:56:05.956180Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = [\n    'Safe Driving',\n    'Texting - Right',\n    'Talking on the Phone - Right',\n    'Texting - Left',\n    'Talking on the Phone - Left',\n    'Operating the Radio',\n    'Drinking',\n    'Reaching Behind',\n    'Hair and Makeup',\n    'Talking to Passenger'\n]","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:05.958903Z","iopub.execute_input":"2024-10-11T17:56:05.959553Z","iopub.status.idle":"2024-10-11T17:56:05.964466Z","shell.execute_reply.started":"2024-10-11T17:56:05.959511Z","shell.execute_reply":"2024-10-11T17:56:05.963448Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"training_images_dir_base = '/kaggle/input/state-farm-distracted-driver-detection/imgs/train'\nnum_samples = 3\nnum_classes = 10\nimage_counts = []\n\nfig, axes = plt.subplots(num_classes, num_samples, figsize=(15, 20))\nfor j in range(num_classes):\n    training_images_dir = f\"{training_images_dir_base}/c{j}\"\n    image_files = os.listdir(training_images_dir)\n    num_images = len(image_files)\n    image_counts.append(num_images)\n    print(f'Class {j}: {num_images} images')\n    rand_images = random.sample(image_files, num_samples) # Display 9 random images\n\n    for i in range(num_samples):\n        image = rand_images[i]\n        ax = axes[j, i]\n        ax.imshow(plt.imread(os.path.join(training_images_dir, image)))\n        ax.set_title(f'{class_names[j]}, Image {i + 1}')\n        ax.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:05.966027Z","iopub.execute_input":"2024-10-11T17:56:05.966747Z","iopub.status.idle":"2024-10-11T17:56:14.967267Z","shell.execute_reply.started":"2024-10-11T17:56:05.966711Z","shell.execute_reply":"2024-10-11T17:56:14.965646Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"total_images = sum(image_counts)\nprint(f'Total number of images across all classes in training directory: {total_images}')","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:14.969112Z","iopub.execute_input":"2024-10-11T17:56:14.969483Z","iopub.status.idle":"2024-10-11T17:56:14.975058Z","shell.execute_reply.started":"2024-10-11T17:56:14.969445Z","shell.execute_reply":"2024-10-11T17:56:14.973908Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install ultralytics\nfrom ultralytics import YOLO ","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:14.977922Z","iopub.execute_input":"2024-10-11T17:56:14.978374Z","iopub.status.idle":"2024-10-11T17:56:34.679616Z","shell.execute_reply.started":"2024-10-11T17:56:14.978309Z","shell.execute_reply":"2024-10-11T17:56:34.678471Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = YOLO(\"yolov5n.pt\") ","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:34.681120Z","iopub.execute_input":"2024-10-11T17:56:34.681807Z","iopub.status.idle":"2024-10-11T17:56:35.478493Z","shell.execute_reply.started":"2024-10-11T17:56:34.681765Z","shell.execute_reply":"2024-10-11T17:56:35.477445Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image  # Import Image from PIL\nimport cv2  # Import cv2 for image processing\nimage = '/kaggle/input/state-farm-distracted-driver-detection/imgs/train/c0/img_10003.jpg'\nresult_predict = model.predict(source = image, imgsz=(416))\n\n# show results\nplot = result_predict[0].plot()\nplot = cv2.cvtColor(plot, cv2.COLOR_BGR2RGB)\ndisplay(Image.fromarray(plot))","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:35.479848Z","iopub.execute_input":"2024-10-11T17:56:35.480192Z","iopub.status.idle":"2024-10-11T17:56:38.113627Z","shell.execute_reply.started":"2024-10-11T17:56:35.480156Z","shell.execute_reply":"2024-10-11T17:56:38.112666Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nimport random\n\n# Source directory (read-only)\nsource_dir = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train\"\n\n# Destination directory (writable)\ndestination_dir = \"/kaggle/working/train\"\n\n# Copy the train directory to the working directory\nshutil.copytree(source_dir, destination_dir)\n\n# Validation directory\nval_dir = '/kaggle/working/validation'\nval_split_ratio = 0.2  # 20% for validation\n\n# Create validation directory if it doesn't exist\nos.makedirs(val_dir, exist_ok=True)\n\n# Loop through each class folder in the copied training directory\nfor class_name in os.listdir(destination_dir):\n    class_path = os.path.join(destination_dir, class_name)\n    \n    if os.path.isdir(class_path):  # Check if it's a directory\n        # Get all images in the class directory\n        images = os.listdir(class_path)\n        random.shuffle(images)  # Shuffle the images\n        \n        # Calculate the number of images to move to validation\n        num_val_images = int(len(images) * val_split_ratio)\n        val_images = images[:num_val_images]  # Select images for validation\n\n        # Create a validation subfolder for the current class\n        val_class_dir = os.path.join(val_dir, class_name)\n        os.makedirs(val_class_dir, exist_ok=True)\n\n        # Copy the selected images to the validation folder and remove from training\n        for img in val_images:\n            src_img_path = os.path.join(class_path, img)\n            dest_img_path = os.path.join(val_class_dir, img)\n            shutil.copy(src_img_path, dest_img_path)  # Copy to validation\n            \n            # Remove the image from the training set\n            os.remove(src_img_path)  # Delete from the training directory\n\n# Function to count total images in a directory\ndef count_images(directory):\n    total_images = 0\n    for class_name in os.listdir(directory):\n        class_path = os.path.join(directory, class_name)\n        if os.path.isdir(class_path):  # Check if it's a directory\n            total_images += len(os.listdir(class_path))  # Count images in the class folder\n    return total_images\n\n# Count training images\ntotal_training_images = count_images(destination_dir)\nprint(f\"Total training images: {total_training_images}\")\n\n# Count validation images\ntotal_validation_images = count_images(val_dir)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:56:38.115478Z","iopub.execute_input":"2024-10-11T17:56:38.115986Z","iopub.status.idle":"2024-10-11T17:59:55.473935Z","shell.execute_reply.started":"2024-10-11T17:56:38.115926Z","shell.execute_reply":"2024-10-11T17:59:55.472874Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Count validation images\ntotal_validation_images = count_images(val_dir)\nprint(f\"Total training images: {total_validation_images}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:59:55.475387Z","iopub.execute_input":"2024-10-11T17:59:55.475745Z","iopub.status.idle":"2024-10-11T17:59:55.485045Z","shell.execute_reply.started":"2024-10-11T17:59:55.475708Z","shell.execute_reply":"2024-10-11T17:59:55.484002Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = YOLO('yolov8n-cls.pt')","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:59:55.486339Z","iopub.execute_input":"2024-10-11T17:59:55.486716Z","iopub.status.idle":"2024-10-11T17:59:56.147913Z","shell.execute_reply.started":"2024-10-11T17:59:55.486679Z","shell.execute_reply":"2024-10-11T17:59:56.146965Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.train(data='/kaggle/working/', epochs=15, imgsz=224)","metadata":{"execution":{"iopub.status.busy":"2024-10-11T17:59:56.149350Z","iopub.execute_input":"2024-10-11T17:59:56.149728Z","iopub.status.idle":"2024-10-11T18:33:25.355175Z","shell.execute_reply.started":"2024-10-11T17:59:56.149690Z","shell.execute_reply":"2024-10-11T18:33:25.354197Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n#Reading results from the csv\nResult_Final_model = pd.read_csv('/kaggle/working/runs/classify/train/results.csv')\nResult_Final_model.tail(5)","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:33:25.356827Z","iopub.execute_input":"2024-10-11T18:33:25.357219Z","iopub.status.idle":"2024-10-11T18:33:25.383085Z","shell.execute_reply.started":"2024-10-11T18:33:25.357182Z","shell.execute_reply":"2024-10-11T18:33:25.382062Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Valid_model = YOLO('/kaggle/working/runs/classify/train/weights/best.pt')","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:37:30.067882Z","iopub.execute_input":"2024-10-11T18:37:30.068296Z","iopub.status.idle":"2024-10-11T18:37:30.103798Z","shell.execute_reply.started":"2024-10-11T18:37:30.068257Z","shell.execute_reply":"2024-10-11T18:37:30.102728Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset_path = '/kaggle/input/state-farm-distracted-driver-detection/imgs' \ntest_images_path = os.path.join(dataset_path, 'test')\n\n# List of all jpg images in the directory\nimage_files = [file for file in os.listdir(test_images_path) if file.endswith('.jpg')]","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:37:33.082085Z","iopub.execute_input":"2024-10-11T18:37:33.083028Z","iopub.status.idle":"2024-10-11T18:37:37.033110Z","shell.execute_reply.started":"2024-10-11T18:37:33.082982Z","shell.execute_reply":"2024-10-11T18:37:37.032173Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if len(image_files) > 0:\n    # Select 9 images at equal intervals\n    num_images = len(image_files)\n    step_size = max(1, num_images // 9)  # Ensure the interval is at least 1\n    selected_images = [image_files[i] for i in range(0, num_images, step_size)]\n\n    # Prepare subplots\n    fig, axes = plt.subplots(3, 3, figsize=(20, 21))\n    fig.suptitle('Validation Set Inferences', fontsize=24)\n\n    for i, ax in enumerate(axes.flatten()):\n        if i < len(selected_images):\n            image_path = os.path.join(test_images_path, selected_images[i])\n            # Load image\n            image = cv2.imread(image_path)\n            \n            # Check if the image is loaded correctly\n            if image is not None:\n                # Resize image\n                resized_image = cv2.resize(image, (640, 640))  # Direct resize\n                normalized_image = resized_image / 255.0  # Normalize\n  \n                \n                # Convert the normalized image to uint8 data type\n                normalized_image_uint8 = (normalized_image * 255).astype(np.uint8)\n                \n                # Predict with the model\n                results = Valid_model.predict(source=normalized_image_uint8, imgsz=640, conf=0.5)\n                \n                # Plot image with labels\n                annotated_image = results[0].plot(line_width=1)\n                annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)\n                ax.imshow(annotated_image_rgb)\n            else:\n                print(f\"Failed to load image {image_path}\")\n        ax.axis('off')\n\n    plt.tight_layout()\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:37:46.902389Z","iopub.execute_input":"2024-10-11T18:37:46.902834Z","iopub.status.idle":"2024-10-11T18:37:51.013813Z","shell.execute_reply.started":"2024-10-11T18:37:46.902793Z","shell.execute_reply":"2024-10-11T18:37:51.012028Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_path =  '/kaggle/input/state-farm-distracted-driver-detection/imgs/train/c0/img_10003.jpg'\nimage = cv2.imread(image_path)\n\nresized_image = cv2.resize(image, (640, 640))  # Direct resize\nnormalized_image = resized_image / 255.0  # Normalize\n\nresult_predict = Valid_model.predict(source = image, imgsz=(640), conf=0.5) #the default image size\n\n# show results\nplot = result_predict[0].plot()\nplot = cv2.cvtColor(plot, cv2.COLOR_BGR2RGB)\ndisplay(Image.fromarray(plot))","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:38:03.774990Z","iopub.execute_input":"2024-10-11T18:38:03.775383Z","iopub.status.idle":"2024-10-11T18:38:03.858471Z","shell.execute_reply.started":"2024-10-11T18:38:03.775346Z","shell.execute_reply":"2024-10-11T18:38:03.857367Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset_path = '/kaggle/input/state-farm-distracted-driver-detection/imgs' \ntest_images_path = os.path.join(dataset_path, 'test')\n\n# List of all jpg images in the directory\nimage_files = [file for file in os.listdir(test_images_path)]","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:38:13.034034Z","iopub.execute_input":"2024-10-11T18:38:13.034851Z","iopub.status.idle":"2024-10-11T18:38:13.083012Z","shell.execute_reply.started":"2024-10-11T18:38:13.034808Z","shell.execute_reply":"2024-10-11T18:38:13.081884Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission2_df.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-11T18:33:26.451024Z","iopub.status.idle":"2024-10-11T18:33:26.451588Z","shell.execute_reply.started":"2024-10-11T18:33:26.451288Z","shell.execute_reply":"2024-10-11T18:33:26.451317Z"},"trusted":true},"outputs":[],"execution_count":null}]}