{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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":5048,"databundleVersionId":868335,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":14234408,"sourceType":"datasetVersion","datasetId":9081233}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Pip install method (recommended)\n\n!pip install ultralytics==8.2.103 -q\n# prevent ultralytics from tracking your activity\n!yolo settings sync=False\nfrom IPython import display\ndisplay.clear_output()\n\nimport ultralytics\nultralytics.checks()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T10:54:12.398612Z","iopub.execute_input":"2025-12-20T10:54:12.39933Z","iopub.status.idle":"2025-12-20T10:54:19.404981Z","shell.execute_reply.started":"2025-12-20T10:54:12.399303Z","shell.execute_reply":"2025-12-20T10:54:19.404227Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Split Dataset For Yolo FORMAT","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport os, shutil\nfrom sklearn.model_selection import train_test_split\n\ncsv_path = \"/kaggle/input/state-farm-distracted-driver-detection/driver_imgs_list.csv\"\nimg_root = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train\"\n\ndf = pd.read_csv(csv_path)\n\ndrivers = df['subject'].unique()\ntrain_drivers, val_drivers = train_test_split(\n    drivers, test_size=0.2, random_state=42\n)\n\ndef copy_images(subset, out_dir):\n    for _, row in subset.iterrows():\n        src = f\"{img_root}/{row.classname}/{row.img}\"\n        dst = f\"{out_dir}/{row.classname}/{row.img}\"\n        os.makedirs(os.path.dirname(dst), exist_ok=True)\n        shutil.copy(src, dst)\n\ncopy_images(df[df.subject.isin(train_drivers)], \"statefarm_yolo/train\")\ncopy_images(df[df.subject.isin(val_drivers)], \"statefarm_yolo/val\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Traiining","metadata":{}},{"cell_type":"code","source":"from ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n-cls.pt\")\n\nmodel.train(\n    data=\"statefarm_yolo\",\n    epochs=25,\n    imgsz=224,\n    batch=64,\n   \n)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:02:12.221773Z","iopub.execute_input":"2025-12-20T09:02:12.222069Z","iopub.status.idle":"2025-12-20T09:39:40.041634Z","shell.execute_reply.started":"2025-12-20T09:02:12.222042Z","shell.execute_reply":"2025-12-20T09:39:40.040666Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" ## Evaluation","metadata":{}},{"cell_type":"code","source":"from IPython.display import Image, display\n\ndisplay(Image(filename=\"runs/classify/train8/results.png\"))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:42:11.099388Z","iopub.execute_input":"2025-12-20T09:42:11.100396Z","iopub.status.idle":"2025-12-20T09:42:11.116696Z","shell.execute_reply.started":"2025-12-20T09:42:11.100365Z","shell.execute_reply":"2025-12-20T09:42:11.115739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nresults = pd.read_csv(\"runs/classify/train8/results.csv\")\nresults","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:42:55.430066Z","iopub.execute_input":"2025-12-20T09:42:55.430331Z","iopub.status.idle":"2025-12-20T09:42:55.459068Z","shell.execute_reply.started":"2025-12-20T09:42:55.430306Z","shell.execute_reply":"2025-12-20T09:42:55.458325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results.columns = results.columns.str.strip()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:49:21.676911Z","iopub.execute_input":"2025-12-20T09:49:21.677207Z","iopub.status.idle":"2025-12-20T09:49:21.681847Z","shell.execute_reply.started":"2025-12-20T09:49:21.677183Z","shell.execute_reply":"2025-12-20T09:49:21.681155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.figure(figsize=(10,5))\n\nplt.plot(results.index + 1, results[\"train/loss\"], label=\"Training Loss\")\nplt.plot(results.index + 1, results[\"val/loss\"], label=\"Validation Loss\")\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.title(\"Training vs Validation Loss\")\nplt.legend()\nplt.grid(True)\n\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:49:24.365025Z","iopub.execute_input":"2025-12-20T09:49:24.365395Z","iopub.status.idle":"2025-12-20T09:49:24.607039Z","shell.execute_reply.started":"2025-12-20T09:49:24.36537Z","shell.execute_reply":"2025-12-20T09:49:24.606023Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Confusion Matrix","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8,8))\nplt.imshow(cm)\nplt.title(\"Validation Confusion Matrix\")\nplt.colorbar()\n\nclasses = [f\"c{i}\" for i in range(cm.shape[0])]\nplt.xticks(range(len(classes)), classes, rotation=45)\nplt.yticks(range(len(classes)), classes)\n\n# SAYILARI YAZDIRAN KISIM\nfor i in range(cm.shape[0]):\n    for j in range(cm.shape[1]):\n        plt.text(j, i, cm[i, j],\n                 ha=\"center\", va=\"center\",\n                 color=\"white\" if cm[i, j] > cm.max()/2 else \"black\",\n                 fontsize=10)\n\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\nplt.tight_layout()\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:52:19.520799Z","iopub.execute_input":"2025-12-20T09:52:19.521362Z","iopub.status.idle":"2025-12-20T09:52:19.94659Z","shell.execute_reply.started":"2025-12-20T09:52:19.521337Z","shell.execute_reply":"2025-12-20T09:52:19.945815Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nimport os\n\nmodel = YOLO(\"runs/classify/train8/weights/best.pt\")\n\nval_dir = \"statefarm_yolo/val\"\nclasses = sorted(os.listdir(val_dir))\n\ny_true = []\ny_pred = []\n\nfor cls_idx, cls in enumerate(classes):\n    cls_dir = os.path.join(val_dir, cls)\n    for img in os.listdir(cls_dir):\n        path = os.path.join(cls_dir, img)\n        r = model(path, verbose=False)[0]\n        y_true.append(cls_idx)\n        y_pred.append(r.probs.top1)\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(y_true, y_pred, target_names=classes))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:55:36.588966Z","iopub.execute_input":"2025-12-20T09:55:36.589219Z","iopub.status.idle":"2025-12-20T09:56:21.961934Z","shell.execute_reply.started":"2025-12-20T09:55:36.589202Z","shell.execute_reply":"2025-12-20T09:56:21.961109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nTEST_DIR = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/test\"\n\nclasses = {\n    'c0': 'normal driving',\n    'c1': 'texting - right',\n    'c2': 'talking on the phone - right',\n    'c3': 'texting - left',\n    'c4': 'talking on the phone - left',\n    'c5': 'operating the radio',\n    'c6': 'drinking',\n    'c7': 'reaching behind',\n    'c8': 'hair and makeup',\n    'c9': 'talking to passenger',\n}\n\nimage_files = [f for f in os.listdir(TEST_DIR) if f.endswith(\".jpg\")]\nsample_images = random.sample(image_files, 30)\n\nplt.figure(figsize=(20, 20))\n\nfor i, img_name in enumerate(sample_images):\n    img_path = os.path.join(TEST_DIR, img_name)\n\n    # YOLO classify prediction\n    result = model(img_path, verbose=False)[0]\n\n    pred_idx = result.probs.top1\n    confidence = result.probs.top1conf.item()\n\n    class_key = list(classes.keys())[pred_idx]\n    class_name = classes[class_key]\n\n    # görüntüyü aç\n    img = Image.open(img_path)\n\n    plt.subplot(6, 5, i + 1)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    plt.title(\n        f\"{class_name}\\nconf: {confidence:.2f}\",\n        fontsize=9\n    )\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T09:59:56.260052Z","iopub.execute_input":"2025-12-20T09:59:56.260735Z","iopub.status.idle":"2025-12-20T10:00:02.623988Z","shell.execute_reply.started":"2025-12-20T09:59:56.26071Z","shell.execute_reply":"2025-12-20T10:00:02.622696Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"hair and make up and talking to passenger                                                       safe driving ve operation radio","metadata":{}},{"cell_type":"code","source":"from ultralytics import YOLO\nimport matplotlib.pyplot as plt\nimport cv2\nimport glob\nimport os\n\n# Model (en iyi ağırlık hangisiyse onu kullan)\nmodel = YOLO(\"runs/classify/train8/weights/best.pt\")\n\n# Test klasörü\nimg_dir = \"/kaggle/input/src-test-fotolar/sürücü test fotolari\"\n\n# Görselleri al\nimage_paths = sorted(\n    glob.glob(os.path.join(img_dir, \"*.jpg\")) +\n    glob.glob(os.path.join(img_dir, \"*.png\")) +\n    glob.glob(os.path.join(img_dir, \"*.jpeg\"))\n)\n\n# En fazla 30 tane göster\nimage_paths = image_paths[:30]\n\nplt.figure(figsize=(20, 20))\n\nfor i, img_path in enumerate(image_paths):\n    img = cv2.imread(img_path)\n    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    # Tahmin\n    result = model(img_path, verbose=False)[0]\n    probs = result.probs\n\n    pred_idx = probs.top1\n    conf = probs.top1conf.item()\n    class_key = result.names[pred_idx]\n    class_name = classes[class_key]\n\n    # Plot\n    plt.subplot(5, 6, i + 1)\n    plt.imshow(img_rgb)\n    plt.axis(\"off\")\n    plt.title(f\"{class_name}\\nconf: {conf:.2f}\", fontsize=10)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T10:13:43.635975Z","iopub.execute_input":"2025-12-20T10:13:43.63625Z","iopub.status.idle":"2025-12-20T10:13:44.508098Z","shell.execute_reply.started":"2025-12-20T10:13:43.636231Z","shell.execute_reply":"2025-12-20T10:13:44.505462Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Overfittingi engellemek için","metadata":{}},{"cell_type":"code","source":"from ultralytics import YOLO\n\n# Modeli yükle\nmodel = YOLO(\"yolov8n-cls.pt\")\n\n# Eğitimi dropout ve patience (early stopping) ile başlat\nmodel.train(\n    data=\"statefarm_yolo\",\n    epochs=50,         \n    imgsz=224,\n    batch=64,\n    dropout=0.2,       \n    patience=5,         \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T10:54:57.224957Z","iopub.execute_input":"2025-12-20T10:54:57.225249Z","iopub.status.idle":"2025-12-20T11:12:48.908421Z","shell.execute_reply.started":"2025-12-20T10:54:57.225224Z","shell.execute_reply":"2025-12-20T11:12:48.907115Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nresults = pd.read_csv(\"runs/classify/train10/results.csv\")\nresults.columns = results.columns.str.strip()\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(10,5))\n\nplt.plot(results.index + 1, results[\"train/loss\"], label=\"Training Loss\")\nplt.plot(results.index + 1, results[\"val/loss\"], label=\"Validation Loss\")\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.title(\"Training vs Validation Loss\")\nplt.legend()\nplt.grid(True)\n\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T11:13:30.756561Z","iopub.execute_input":"2025-12-20T11:13:30.757196Z","iopub.status.idle":"2025-12-20T11:13:30.977238Z","shell.execute_reply.started":"2025-12-20T11:13:30.757167Z","shell.execute_reply":"2025-12-20T11:13:30.976306Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Dosya yolu (train10 senin en son eğitim klasörünse)\nimg_path = '/kaggle/working/runs/classify/train10/confusion_matrix.png'\n\ntry:\n    img = mpimg.imread(img_path)\n    plt.figure(figsize=(12, 10))\n    plt.imshow(img)\n    plt.axis('off')\n    plt.title('YOLOv8 Confusion Matrix', fontsize=16)\n    plt.show()\nexcept FileNotFoundError:\n    print(\"Dosya bulunamadı. Lütfen 'train10' klasörünün doğru olduğundan emin ol.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T11:15:37.207753Z","iopub.execute_input":"2025-12-20T11:15:37.208672Z","iopub.status.idle":"2025-12-20T11:15:38.4776Z","shell.execute_reply.started":"2025-12-20T11:15:37.208638Z","shell.execute_reply":"2025-12-20T11:15:38.476897Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nimport os\n\nmodel = YOLO(\"runs/classify/train10/weights/best.pt\")\n\nval_dir = \"statefarm_yolo/val\"\nclasses = sorted(os.listdir(val_dir))\n\ny_true = []\ny_pred = []\n\nfor cls_idx, cls in enumerate(classes):\n    cls_dir = os.path.join(val_dir, cls)\n    for img in os.listdir(cls_dir):\n        path = os.path.join(cls_dir, img)\n        r = model(path, verbose=False)[0]\n        y_true.append(cls_idx)\n        y_pred.append(r.probs.top1)\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(y_true, y_pred, target_names=classes))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T11:17:11.111588Z","iopub.execute_input":"2025-12-20T11:17:11.1122Z","iopub.status.idle":"2025-12-20T11:17:56.468515Z","shell.execute_reply.started":"2025-12-20T11:17:11.112174Z","shell.execute_reply":"2025-12-20T11:17:56.467488Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nTEST_DIR = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/test\"\n\nclasses = {\n    'c0': 'normal driving',\n    'c1': 'texting - right',\n    'c2': 'talking on the phone - right',\n    'c3': 'texting - left',\n    'c4': 'talking on the phone - left',\n    'c5': 'operating the radio',\n    'c6': 'drinking',\n    'c7': 'reaching behind',\n    'c8': 'hair and makeup',\n    'c9': 'talking to passenger',\n}\n\nimage_files = [f for f in os.listdir(TEST_DIR) if f.endswith(\".jpg\")]\nsample_images = random.sample(image_files, 30)\n\nplt.figure(figsize=(20, 20))\n\nfor i, img_name in enumerate(sample_images):\n    img_path = os.path.join(TEST_DIR, img_name)\n\n    # YOLO classify prediction\n    result = model(img_path, verbose=False)[0]\n\n    pred_idx = result.probs.top1\n    confidence = result.probs.top1conf.item()\n\n    class_key = list(classes.keys())[pred_idx]\n    class_name = classes[class_key]\n\n    # görüntüyü aç\n    img = Image.open(img_path)\n\n    plt.subplot(6, 5, i + 1)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    plt.title(\n        f\"{class_name}\\nconf: {confidence:.2f}\",\n        fontsize=9\n    )\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T11:19:37.815476Z","iopub.execute_input":"2025-12-20T11:19:37.8162Z","iopub.status.idle":"2025-12-20T11:19:42.622864Z","shell.execute_reply.started":"2025-12-20T11:19:37.816171Z","shell.execute_reply":"2025-12-20T11:19:42.621487Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"hair and make up and talking to passenger\nsafe driving ve operation radio","metadata":{}},{"cell_type":"code","source":"from ultralytics import YOLO\nimport matplotlib.pyplot as plt\nimport cv2\nimport glob\nimport os\n\n# Model (en iyi ağırlık hangisiyse onu kullan)\nmodel = YOLO(\"runs/classify/train10/weights/best.pt\")\n\n# Test klasörü\nimg_dir = \"/kaggle/input/src-test-fotolar/sürücü test fotolari\"\n\n# Görselleri al\nimage_paths = sorted(\n    glob.glob(os.path.join(img_dir, \"*.jpg\")) +\n    glob.glob(os.path.join(img_dir, \"*.png\")) +\n    glob.glob(os.path.join(img_dir, \"*.jpeg\"))\n)\n\n# En fazla 30 tane göster\nimage_paths = image_paths[:30]\n\nplt.figure(figsize=(20, 20))\n\nfor i, img_path in enumerate(image_paths):\n    img = cv2.imread(img_path)\n    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    # Tahmin\n    result = model(img_path, verbose=False)[0]\n    probs = result.probs\n\n    pred_idx = probs.top1\n    conf = probs.top1conf.item()\n    class_key = result.names[pred_idx]\n    class_name = classes[class_key]\n\n    # Plot\n    plt.subplot(5, 6, i + 1)\n    plt.imshow(img_rgb)\n    plt.axis(\"off\")\n    plt.title(f\"{class_name}\\nconf: {conf:.2f}\", fontsize=10)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T11:20:40.816234Z","iopub.execute_input":"2025-12-20T11:20:40.816629Z","iopub.status.idle":"2025-12-20T11:20:41.707419Z","shell.execute_reply.started":"2025-12-20T11:20:40.816606Z","shell.execute_reply":"2025-12-20T11:20:41.706544Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}