{"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":91249,"databundleVersionId":11294684,"sourceType":"competition"},{"sourceId":316800,"sourceType":"modelInstanceVersion","modelInstanceId":267360,"modelId":288417},{"sourceId":323331,"sourceType":"modelInstanceVersion","modelInstanceId":272385,"modelId":293362}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install ipywidgets\n#!pip install csbdeep\n!pip install ultralytics\nfrom ultralytics import YOLO","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:12.628239Z","iopub.execute_input":"2025-04-08T02:01:12.628536Z","iopub.status.idle":"2025-04-08T02:01:25.689564Z","shell.execute_reply.started":"2025-04-08T02:01:12.628506Z","shell.execute_reply":"2025-04-08T02:01:25.688890Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image, ImageDraw\nimport shutil\nimport time\nimport yaml\nimport json\nimport random\nimport torch\nimport cv2\nimport glob\nfrom multiprocessing import Pool, cpu_count\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nfrom ultralytics import YOLO\nfrom pathlib import Path\nfrom tqdm import tqdm\n\n# Set random seed for reproducibility\nnp.random.seed(42)\nrandom.seed(42)\ntorch.manual_seed(42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:25.690366Z","iopub.execute_input":"2025-04-08T02:01:25.690726Z","iopub.status.idle":"2025-04-08T02:01:26.067439Z","shell.execute_reply.started":"2025-04-08T02:01:25.690705Z","shell.execute_reply":"2025-04-08T02:01:26.066683Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"새 pretrained model 추가","metadata":{}},{"cell_type":"code","source":"# Define Kaggle paths\ndata_path = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/\"\ntrain_dir = os.path.join(data_path, \"train\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.068170Z","iopub.execute_input":"2025-04-08T02:01:26.068600Z","iopub.status.idle":"2025-04-08T02:01:26.071914Z","shell.execute_reply.started":"2025-04-08T02:01:26.068577Z","shell.execute_reply":"2025-04-08T02:01:26.071045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define YOLO dataset structure\nyolo_dataset_dir = \"/kaggle/working/yolo_dataset\"\nyolo_images_train = os.path.join(yolo_dataset_dir, \"images\", \"train\")\nyolo_images_val = os.path.join(yolo_dataset_dir, \"images\", \"val\")\nyolo_labels_train = os.path.join(yolo_dataset_dir, \"labels\", \"train\")\nyolo_labels_val = os.path.join(yolo_dataset_dir, \"labels\", \"val\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.072734Z","iopub.execute_input":"2025-04-08T02:01:26.073014Z","iopub.status.idle":"2025-04-08T02:01:26.089863Z","shell.execute_reply.started":"2025-04-08T02:01:26.072987Z","shell.execute_reply":"2025-04-08T02:01:26.089196Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create directories\nfor dir_path in [yolo_images_train, yolo_images_val, yolo_labels_train, yolo_labels_val]:\n    os.makedirs(dir_path, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.090562Z","iopub.execute_input":"2025-04-08T02:01:26.090781Z","iopub.status.idle":"2025-04-08T02:01:26.104043Z","shell.execute_reply.started":"2025-04-08T02:01:26.090762Z","shell.execute_reply":"2025-04-08T02:01:26.103429Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define constants\nTRUST = 4  # Number of slices above and below center slice (total 2*TRUST + 1 slices)\nBOX_SIZE = 24  # Bounding box size for annotations (in pixels)\nTRAIN_SPLIT = 0.8  # 80% for training, 20% for validation","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.105918Z","iopub.execute_input":"2025-04-08T02:01:26.106106Z","iopub.status.idle":"2025-04-08T02:01:26.118554Z","shell.execute_reply.started":"2025-04-08T02:01:26.106090Z","shell.execute_reply":"2025-04-08T02:01:26.117761Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Image processing functions\ndef normalize_slice(slice_data):\n    \"\"\"\n    Normalize slice data using 2nd and 98th percentiles\n    \"\"\"\n    # Calculate percentiles\n    p2 = np.percentile(slice_data, 2)\n    p98 = np.percentile(slice_data, 98)\n    \n    # Clip the data to the percentile range\n    clipped_data = np.clip(slice_data, p2, p98)\n    \n    # Normalize to [0, 255] range\n    normalized = 255 * (clipped_data - p2) / (p98 - p2)\n    \n    return np.uint8(normalized)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.119666Z","iopub.execute_input":"2025-04-08T02:01:26.119882Z","iopub.status.idle":"2025-04-08T02:01:26.132538Z","shell.execute_reply.started":"2025-04-08T02:01:26.119864Z","shell.execute_reply":"2025-04-08T02:01:26.131887Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"추가 전처리 함수들","metadata":{}},{"cell_type":"code","source":"def prepare_yolo_dataset(trust=TRUST, train_split=TRAIN_SPLIT):\n    \"\"\"\n    Extract slices containing motors from tomograms and save to YOLO structure with annotations\n    \"\"\"\n    # Load the labels CSV\n    labels_df = pd.read_csv(os.path.join(data_path, \"train_labels.csv\"))\n    \n    # Count total number of motors\n    total_motors = labels_df['Number of motors'].sum()\n    print(f\"Total number of motors in the dataset: {total_motors}\")\n    \n    # Get unique tomograms that have motors\n    tomo_df = labels_df[labels_df['Number of motors'] > 0].copy()\n    unique_tomos = tomo_df['tomo_id'].unique()\n    \n    print(f\"Found {len(unique_tomos)} unique tomograms with motors\")\n    \n    # Perform the train-val split at the tomogram level (not motor level)\n    # This ensures all slices from a single tomogram go to either train or val\n    np.random.shuffle(unique_tomos)  # Shuffle the tomograms\n    split_idx = int(len(unique_tomos) * train_split)\n    train_tomos = unique_tomos[:split_idx]\n    val_tomos = unique_tomos[split_idx:]\n    \n    print(f\"Split: {len(train_tomos)} tomograms for training, {len(val_tomos)} tomograms for validation\")\n    \n    # Function to process a set of tomograms\n    def process_tomogram_set(tomogram_ids, images_dir, labels_dir, set_name):\n        motor_counts = []\n        for tomo_id in tomogram_ids:\n            # Get all motors for this tomogram\n            tomo_motors = labels_df[labels_df['tomo_id'] == tomo_id]\n            for _, motor in tomo_motors.iterrows():\n                if pd.isna(motor['Motor axis 0']):\n                    continue\n                motor_counts.append(\n                    (tomo_id, \n                     int(motor['Motor axis 0']), \n                     int(motor['Motor axis 1']), \n                     int(motor['Motor axis 2']),\n                     int(motor['Array shape (axis 0)']))\n                )\n        \n        print(f\"Will process approximately {len(motor_counts) * (2 * trust + 1)} slices for {set_name}\")\n        \n        # Process each motor\n        processed_slices = 0\n        \n        for tomo_id, z_center, y_center, x_center, z_max in tqdm(motor_counts, desc=f\"Processing {set_name} motors\"):\n            # Calculate range of slices to include\n            z_min = max(0, z_center - trust)\n            z_max = min(z_max - 1, z_center + trust)\n            \n            # Process each slice in the range\n            for z in range(z_min, z_max + 1):\n                # Create slice filename\n                slice_filename = f\"slice_{z:04d}.jpg\"\n                \n                # Source path for the slice\n                src_path = os.path.join(train_dir, tomo_id, slice_filename)\n                \n                if not os.path.exists(src_path):\n                    print(f\"Warning: {src_path} does not exist, skipping.\")\n                    continue\n                \n                # Load and normalize the slice\n                img = Image.open(src_path)\n                img_array = np.array(img)\n                \n                # Normalize the image\n                normalized_img = normalize_slice(img_array) # <- 바로 위의 normalize 함수 사용\n\n                final_img = normalized_img\n                \n                # Create destination filename (with unique identifier)\n                dest_filename = f\"{tomo_id}_z{z:04d}_y{y_center:04d}_x{x_center:04d}.jpg\"\n                dest_path = os.path.join(images_dir, dest_filename)\n                \n                # Save the normalized image\n                Image.fromarray(final_img).save(dest_path)\n                \n                # Get image dimensions\n                img_width, img_height = img.size\n                \n                # Create YOLO format label\n                # YOLO format: <class> <x_center> <y_center> <width> <height>\n                # Values are normalized to [0, 1]\n                x_center_norm = x_center / img_width\n                y_center_norm = y_center / img_height\n                box_width_norm = BOX_SIZE / img_width\n                box_height_norm = BOX_SIZE / img_height\n                \n                # Write label file\n                label_path = os.path.join(labels_dir, dest_filename.replace('.jpg', '.txt'))\n                with open(label_path, 'w') as f:\n                    f.write(f\"0 {x_center_norm} {y_center_norm} {box_width_norm} {box_height_norm}\\n\")\n                \n                processed_slices += 1\n        \n        return processed_slices, len(motor_counts)\n    \n    # Process training tomograms\n    train_slices, train_motors = process_tomogram_set(train_tomos, yolo_images_train, yolo_labels_train, \"training\")\n    \n    # Process validation tomograms\n    val_slices, val_motors = process_tomogram_set(val_tomos, yolo_images_val, yolo_labels_val, \"validation\")\n    \n    # Create YAML configuration file for YOLO\n    yaml_content = {\n        'path': yolo_dataset_dir,\n        'train': 'images/train',\n        'val': 'images/val',\n        'names': {0: 'motor'}\n    }\n    \n    with open(os.path.join(yolo_dataset_dir, 'dataset.yaml'), 'w') as f:\n        yaml.dump(yaml_content, f, default_flow_style=False)\n    \n    print(f\"\\nProcessing Summary:\")\n    print(f\"- Train set: {len(train_tomos)} tomograms, {train_motors} motors, {train_slices} slices\")\n    print(f\"- Validation set: {len(val_tomos)} tomograms, {val_motors} motors, {val_slices} slices\")\n    print(f\"- Total: {len(train_tomos) + len(val_tomos)} tomograms, {train_motors + val_motors} motors, {train_slices + val_slices} slices\")\n    \n    # Return summary info\n    return {\n        \"dataset_dir\": yolo_dataset_dir,\n        \"yaml_path\": os.path.join(yolo_dataset_dir, 'dataset.yaml'),\n        \"train_tomograms\": len(train_tomos),\n        \"val_tomograms\": len(val_tomos),\n        \"train_motors\": train_motors,\n        \"val_motors\": val_motors,\n        \"train_slices\": train_slices,\n        \"val_slices\": val_slices\n    }","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.133206Z","iopub.execute_input":"2025-04-08T02:01:26.133482Z","iopub.status.idle":"2025-04-08T02:01:26.148058Z","shell.execute_reply.started":"2025-04-08T02:01:26.133463Z","shell.execute_reply":"2025-04-08T02:01:26.147303Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Run the preprocessing\nsummary = prepare_yolo_dataset(TRUST)\nprint(f\"\\nPreprocessing Complete:\")\nprint(f\"- Training data: {summary['train_tomograms']} tomograms, {summary['train_motors']} motors, {summary['train_slices']} slices\")\nprint(f\"- Validation data: {summary['val_tomograms']} tomograms, {summary['val_motors']} motors, {summary['val_slices']} slices\")\nprint(f\"- Dataset directory: {summary['dataset_dir']}\")\nprint(f\"- YAML configuration: {summary['yaml_path']}\")\nprint(f\"\\nReady for YOLO training!\") ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:01:26.148849Z","iopub.execute_input":"2025-04-08T02:01:26.149096Z","iopub.status.idle":"2025-04-08T02:04:21.422393Z","shell.execute_reply.started":"2025-04-08T02:01:26.149068Z","shell.execute_reply":"2025-04-08T02:04:21.421661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define base_dir - this was missing in the original code\n# In Kaggle, we can use the working directory as base or remove it completely\n# since we're using absolute paths\nbase_dir = \"/kaggle/working\"  # or simply use \"\" if using absolute paths\n\n# Updated paths without concatenating with base_dir since they're already absolute\nimages_train_dir = \"/kaggle/working/yolo_dataset/images/train/\"\nlabels_train_dir = \"/kaggle/working/yolo_dataset/labels/train/\"\n\ndef visualize_random_training_samples(num_samples=4):\n    \"\"\"\n    Visualize random training samples with YOLO annotations\n    \n    Args:\n        num_samples (int): Number of random images to display\n    \"\"\"\n    # Get all image files from the train directory\n    image_files = []\n    for ext in ['*.jpg', '*.jpeg', '*.png']:\n        image_files.extend(glob.glob(os.path.join(images_train_dir, \"**\", ext), recursive=True))\n    \n    # Make sure we have enough images\n    if len(image_files) == 0:\n        print(\"No image files found in the train directory!\")\n        return\n        \n    num_samples = min(num_samples, len(image_files))\n    \n    # Select random images\n    random_images = random.sample(image_files, num_samples)\n    \n    # Create a figure with subplots\n    rows = int(np.ceil(num_samples / 2))\n    cols = min(num_samples, 2)\n    fig, axes = plt.subplots(rows, cols, figsize=(14, 5 * rows))\n    \n    # Handle the case of a single subplot\n    if num_samples == 1:\n        axes = np.array([axes])\n    \n    # Flatten axes array for easy indexing\n    axes = axes.flatten()\n    \n    # Process each selected image\n    for i, img_path in enumerate(random_images):\n        try:\n            # Get corresponding label file\n            # YOLO labels have same name but .txt extension instead of image extension\n            relative_path = os.path.relpath(img_path, images_train_dir)\n            label_path = os.path.join(labels_train_dir, os.path.splitext(relative_path)[0] + '.txt')\n            \n            # Load the image\n            img = Image.open(img_path)\n            img_width, img_height = img.size\n            \n            # Normalize image using percentiles for better visualization\n            img_array = np.array(img)\n            p2 = np.percentile(img_array, 2)\n            p98 = np.percentile(img_array, 98)\n            normalized = np.clip(img_array, p2, p98)\n            normalized = 255 * (normalized - p2) / (p98 - p2)\n            img_normalized = Image.fromarray(np.uint8(normalized))\n            \n            # Convert image to RGB for colored box\n            img_rgb = img_normalized.convert('RGB')\n            \n            # Create a transparent overlay\n            overlay = Image.new('RGBA', img_rgb.size, (0, 0, 0, 0))\n            draw = ImageDraw.Draw(overlay)\n            \n            # Load YOLO format annotations if they exist\n            annotations = []\n            if os.path.exists(label_path):\n                with open(label_path, 'r') as f:\n                    for line in f:\n                        # YOLO format: class x_center y_center width height\n                        # All values are normalized from 0 to 1\n                        values = line.strip().split()\n                        class_id = int(values[0])\n                        x_center = float(values[1]) * img_width\n                        y_center = float(values[2]) * img_height\n                        width = float(values[3]) * img_width\n                        height = float(values[4]) * img_height\n                        \n                        annotations.append({\n                            'class_id': class_id,\n                            'x_center': x_center,\n                            'y_center': y_center,\n                            'width': width,\n                            'height': height\n                        })\n            \n            # Draw all annotations\n            for ann in annotations:\n                x_center = ann['x_center']\n                y_center = ann['y_center']\n                width = ann['width']\n                height = ann['height']\n                \n                # Calculate bounding box coordinates\n                x1 = max(0, int(x_center - width/2))\n                y1 = max(0, int(y_center - height/2))\n                x2 = min(img_width, int(x_center + width/2))\n                y2 = min(img_height, int(y_center + height/2))\n                \n                # Draw semi-transparent red rectangle\n                draw.rectangle([x1, y1, x2, y2], fill=(255, 0, 0, 64), outline=(255, 0, 0, 200))\n                \n                # Draw label\n                label_text = f\"Class {ann['class_id']}\"\n                draw.text((x1, y1-10), label_text, fill=(255, 0, 0, 255))\n            \n            # If no annotations found, indicate this\n            if not annotations:\n                draw.text((10, 10), \"No annotations found\", fill=(255, 0, 0, 255))\n            \n            # Composite the overlay onto the original image\n            img_rgb = Image.alpha_composite(img_rgb.convert('RGBA'), overlay).convert('RGB')\n            \n            # Display the image with annotations\n            axes[i].imshow(np.array(img_rgb))\n            img_name = os.path.basename(img_path)\n            axes[i].set_title(f\"Image: {img_name}\\nAnnotations: {len(annotations)}\")\n            axes[i].axis('on')\n            \n        except Exception as e:\n            print(f\"Error processing image {img_path}: {e}\")\n            axes[i].text(0.5, 0.5, f\"Error loading image: {os.path.basename(img_path)}\", \n                       horizontalalignment='center', verticalalignment='center')\n            axes[i].axis('off')\n    \n    # Handle extra subplots if any\n    for j in range(i + 1, len(axes)):\n        axes[j].axis('off')\n    \n    plt.tight_layout()\n    plt.show()\n    \n    # Print summary\n    print(f\"Displayed {num_samples} random images with YOLO annotations\")\n\n# Run the visualization\nvisualize_random_training_samples(4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:04:21.423262Z","iopub.execute_input":"2025-04-08T02:04:21.423526Z","iopub.status.idle":"2025-04-08T02:04:22.931131Z","shell.execute_reply.started":"2025-04-08T02:04:21.423504Z","shell.execute_reply":"2025-04-08T02:04:22.930236Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"data 전처리","metadata":{}},{"cell_type":"code","source":"def denoise_dncnn(img_np):\n    denoised = cv2.fastNlMeansDenoising(\n    src=gray_img,              # 입력 이미지 (uint8)\n    h=20,                      # 필터 강도 (값이 높을수록 더 부드러움)\n    templateWindowSize=7,      # 기본값: 7\n    searchWindowSize=21        # 기본값: 21\n)\n\n    return result.astype(np.uint8)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:04:23.258481Z","iopub.execute_input":"2025-04-08T02:04:23.258729Z","iopub.status.idle":"2025-04-08T02:04:23.263261Z","shell.execute_reply.started":"2025-04-08T02:04:23.258709Z","shell.execute_reply":"2025-04-08T02:04:23.262489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ 이미지 경로\nimg_paths = sorted(glob.glob(os.path.join(images_train_dir, '*.jpg')))\n\n# ✅ 디노이즈하고 원본에 덮어쓰기\nprocessed_paths = []\n\nfor path in tqdm(img_paths, desc='DnCNN 디노이즈 중'):\n    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    if img is None:\n        continue\n    try:\n        denoised = denoise_dncnn(img)\n        cv2.imwrite(path, denoised)\n        processed_paths.append(path)\n    except Exception as e:\n        print(f\"❌ 에러: {path} → {e}\")\n\nprint(f\"✅ 디노이즈 및 덮어쓰기 완료: 총 {len(processed_paths)}장\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:04:23.264007Z","iopub.execute_input":"2025-04-08T02:04:23.264189Z","iopub.status.idle":"2025-04-08T02:11:12.396483Z","shell.execute_reply.started":"2025-04-08T02:04:23.264173Z","shell.execute_reply":"2025-04-08T02:11:12.395635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ 3~4장 시각화\nnum_show = 4\nsample_paths = random.sample(processed_paths, min(num_show, len(processed_paths)))\n\nplt.figure(figsize=(10, 4 * len(sample_paths)))\n\nfor i, path in enumerate(sample_paths):\n    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    if img is None:\n        continue\n    plt.subplot(len(sample_paths), 1, i + 1)\n    plt.imshow(img, cmap='gray', vmin=0, vmax=255)\n    plt.title(f'Denoised: {os.path.basename(path)}')\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:12.397285Z","iopub.execute_input":"2025-04-08T02:11:12.397567Z","iopub.status.idle":"2025-04-08T02:11:13.102366Z","shell.execute_reply.started":"2025-04-08T02:11:12.397544Z","shell.execute_reply":"2025-04-08T02:11:13.101312Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"yolo","metadata":{}},{"cell_type":"code","source":"# Define paths for Kaggle environment\nyolo_weights_dir = \"/kaggle/working/yolo_weights\"\nyolo_pretrained_weights = \"/kaggle/input/y8/pytorch/default/1/best.pt\"  # Path to pre-downloaded weights\n\n# Create weights directory if it doesn't exist\nos.makedirs(yolo_weights_dir, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.103257Z","iopub.execute_input":"2025-04-08T02:11:13.103529Z","iopub.status.idle":"2025-04-08T02:11:13.107329Z","shell.execute_reply.started":"2025-04-08T02:11:13.103504Z","shell.execute_reply":"2025-04-08T02:11:13.106387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def fix_yaml_paths(yaml_path):\n    \"\"\"\n    Fix the paths in the YAML file to match the actual Kaggle directories\n    \n    Args:\n        yaml_path (str): Path to the original dataset YAML file\n        \n    Returns:\n        str: Path to the fixed YAML file\n    \"\"\"\n    print(f\"Fixing YAML paths in {yaml_path}\")\n    \n    # Read the original YAML\n    with open(yaml_path, 'r') as f:\n        yaml_data = yaml.safe_load(f)\n    \n    # Update paths to use actual dataset location\n    if 'path' in yaml_data:\n        yaml_data['path'] = yolo_dataset_dir\n    \n    # Create a new fixed YAML in the working directory\n    fixed_yaml_path = \"/kaggle/working/fixed_dataset.yaml\"\n    with open(fixed_yaml_path, 'w') as f:\n        yaml.dump(yaml_data, f)\n    \n    print(f\"Created fixed YAML at {fixed_yaml_path} with path: {yaml_data.get('path')}\")\n    return fixed_yaml_path","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.108181Z","iopub.execute_input":"2025-04-08T02:11:13.108462Z","iopub.status.idle":"2025-04-08T02:11:13.122259Z","shell.execute_reply.started":"2025-04-08T02:11:13.108434Z","shell.execute_reply":"2025-04-08T02:11:13.121479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_dfl_loss_curve(run_dir):\n    \"\"\"\n    Plot the DFL loss curves for train and validation, marking the best model\n    \n    Args:\n        run_dir (str): Directory where the training results are stored\n    \"\"\"\n    # Path to the results CSV file\n    results_csv = os.path.join(run_dir, 'results.csv')\n    \n    if not os.path.exists(results_csv):\n        print(f\"Results file not found at {results_csv}\")\n        return\n    \n    # Read results CSV\n    results_df = pd.read_csv(results_csv)\n    \n    # Check if DFL loss columns exist\n    train_dfl_col = [col for col in results_df.columns if 'train/dfl_loss' in col]\n    val_dfl_col = [col for col in results_df.columns if 'val/dfl_loss' in col]\n    \n    if not train_dfl_col or not val_dfl_col:\n        print(\"DFL loss columns not found in results CSV\")\n        print(f\"Available columns: {results_df.columns.tolist()}\")\n        return\n    \n    train_dfl_col = train_dfl_col[0]\n    val_dfl_col = val_dfl_col[0]\n    \n    # Find the epoch with the best validation loss\n    best_epoch = results_df[val_dfl_col].idxmin()\n    best_val_loss = results_df.loc[best_epoch, val_dfl_col]\n    \n    # Create the plot\n    plt.figure(figsize=(10, 6))\n    \n    # Plot training and validation losses\n    plt.plot(results_df['epoch'], results_df[train_dfl_col], label='Train DFL Loss')\n    plt.plot(results_df['epoch'], results_df[val_dfl_col], label='Validation DFL Loss')\n    \n    # Mark the best model with a vertical line\n    plt.axvline(x=results_df.loc[best_epoch, 'epoch'], color='r', linestyle='--', \n                label=f'Best Model (Epoch {int(results_df.loc[best_epoch, \"epoch\"])}, Val Loss: {best_val_loss:.4f})')\n    \n    # Add labels and legend\n    plt.xlabel('Epoch')\n    plt.ylabel('DFL Loss')\n    plt.title('Training and Validation DFL Loss')\n    plt.legend()\n    plt.grid(True, linestyle='--', alpha=0.7)\n    \n    # Save the plot in the same directory as weights\n    plot_path = os.path.join(run_dir, 'dfl_loss_curve.png')\n    plt.savefig(plot_path)\n    \n    # Also save it to the working directory for easier access\n    plt.savefig(os.path.join('/kaggle/working', 'dfl_loss_curve.png'))\n    \n    print(f\"Loss curve saved to {plot_path}\")\n    plt.close()\n    \n    # Return the best epoch info\n    return best_epoch, best_val_loss","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.123112Z","iopub.execute_input":"2025-04-08T02:11:13.123392Z","iopub.status.idle":"2025-04-08T02:11:13.139851Z","shell.execute_reply.started":"2025-04-08T02:11:13.123364Z","shell.execute_reply":"2025-04-08T02:11:13.139165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_yolo_model(yaml_path, pretrained_weights_path , epochs=5, batch_size=16, img_size=640):\n    \"\"\"\n    Train a YOLO model on the prepared dataset\n    \n    Args:\n        yaml_path (str): Path to the dataset YAML file\n        pretrained_weights_path (str): Path to pre-downloaded weights file\n        epochs (int): Number of training epochs\n        batch_size (int): Batch size for training\n        img_size (int): Image size for training\n    \"\"\"\n    print(f\"Loading pre-trained weights from: {pretrained_weights_path}\")\n\n    # Load a pre-trained YOLOv8 model\n    model = YOLO(pretrained_weights_path)\n    \n    # Train the model with early stopping\n    results = model.train(\n        data=yaml_path,\n        epochs=epochs,\n        batch=batch_size,\n        imgsz=img_size,\n        project=yolo_weights_dir,\n        name='motor_detector',\n        exist_ok=True,\n        patience=10,              # Early stopping if no improvement for 5 epochs\n        save_period=5,           # Save checkpoints every 5 epochs\n        val=True,                # Ensure validation is performed\n        verbose=True,             # Show detailed output during training\n        lr0=0.001,\n        optimizer='AdamW'\n    )\n    \n    # Get the path to the run directory\n    run_dir = os.path.join(yolo_weights_dir, 'motor_detector')\n    \n    # Plot and save the loss curve\n    best_epoch_info = plot_dfl_loss_curve(run_dir)\n    \n    if best_epoch_info:\n        best_epoch, best_val_loss = best_epoch_info\n        print(f\"\\nBest model found at epoch {best_epoch} with validation DFL loss: {best_val_loss:.4f}\")\n    \n    return model, results","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.142385Z","iopub.execute_input":"2025-04-08T02:11:13.142668Z","iopub.status.idle":"2025-04-08T02:11:13.157223Z","shell.execute_reply.started":"2025-04-08T02:11:13.142637Z","shell.execute_reply":"2025-04-08T02:11:13.156528Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Check and create a dataset YAML if needed\ndef prepare_dataset():\n    \"\"\"\n    Check if dataset exists and create a proper YAML if needed\n    \n    Returns:\n        str: Path to the YAML file to use for training\n    \"\"\"\n    # Check if images exist\n    train_images_dir = os.path.join(yolo_dataset_dir, 'images', 'train')\n    val_images_dir = os.path.join(yolo_dataset_dir, 'images', 'val')\n    train_labels_dir = os.path.join(yolo_dataset_dir, 'labels', 'train')\n    val_labels_dir = os.path.join(yolo_dataset_dir, 'labels', 'val')\n    \n    # Print directory existence status\n    print(f\"Directory status:\")\n    print(f\"- Train images dir exists: {os.path.exists(train_images_dir)}\")\n    print(f\"- Val images dir exists: {os.path.exists(val_images_dir)}\")\n    print(f\"- Train labels dir exists: {os.path.exists(train_labels_dir)}\")\n    print(f\"- Val labels dir exists: {os.path.exists(val_labels_dir)}\")\n    \n    # Check for original YAML file\n    original_yaml_path = os.path.join(yolo_dataset_dir, 'dataset.yaml')\n    \n    if os.path.exists(original_yaml_path):\n        print(f\"Found original dataset.yaml at {original_yaml_path}\")\n        # Fix the paths in the YAML\n        return fix_yaml_paths(original_yaml_path)\n    else:\n        print(f\"Original dataset.yaml not found, creating a new one\")\n        \n        # Create a new YAML file\n        yaml_data = {\n            'path': yolo_dataset_dir,\n            'train': 'images/train',\n            'val': 'images/train' if not os.path.exists(val_images_dir) else 'images/val',\n            'names': {0: 'motor'}\n        }\n        \n        new_yaml_path = \"/kaggle/working/yolo_dataset/dataset.yaml\"\n        with open(new_yaml_path, 'w') as f:\n            yaml.dump(yaml_data, f)\n            \n        print(f\"Created new YAML at {new_yaml_path}\")\n        return new_yaml_path","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.158119Z","iopub.execute_input":"2025-04-08T02:11:13.158333Z","iopub.status.idle":"2025-04-08T02:11:13.174509Z","shell.execute_reply.started":"2025-04-08T02:11:13.158314Z","shell.execute_reply":"2025-04-08T02:11:13.173688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Main execution\ndef main():\n    print(\"Starting YOLO training process...\")\n    \n    # Prepare dataset and get YAML path\n    yaml_path = prepare_dataset()\n    print(f\"Using YAML file: {yaml_path}\")\n    \n    # Print YAML file contents\n    with open(yaml_path, 'r') as f:\n        yaml_content = f.read()\n    print(f\"YAML file contents:\\n{yaml_content}\")\n    \n    # Train model\n    print(\"\\nStarting YOLO training...\")\n    model, results = train_yolo_model(\n        yaml_path,\n        pretrained_weights_path=yolo_pretrained_weights,\n        epochs= 5,  # Using 30 epochs instead of 100 for faster training\n    )\n    \n    print(\"\\nTraining complete!\")  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.175204Z","iopub.execute_input":"2025-04-08T02:11:13.175480Z","iopub.status.idle":"2025-04-08T02:11:13.185811Z","shell.execute_reply.started":"2025-04-08T02:11:13.175455Z","shell.execute_reply":"2025-04-08T02:11:13.185156Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = YOLO(yolo_pretrained_weights)\n# 전체 레이어 확인 (선택 사항)\nfor name, param in model.model.named_parameters():\n    print(name)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:13.186689Z","iopub.execute_input":"2025-04-08T02:11:13.186928Z","iopub.status.idle":"2025-04-08T02:11:14.084350Z","shell.execute_reply.started":"2025-04-08T02:11:13.186909Z","shell.execute_reply":"2025-04-08T02:11:14.083485Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 예: backbone만 freeze하고, head만 fine-tuning 하고 싶을 때\nfor name, param in model.model.named_parameters():\n    if \"22\" in name:\n        param.requires_grad = True  # freeze backbone\n    else:\n        param.requires_grad = False   # train head","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:14.085298Z","iopub.execute_input":"2025-04-08T02:11:14.085595Z","iopub.status.idle":"2025-04-08T02:11:14.090392Z","shell.execute_reply.started":"2025-04-08T02:11:14.085553Z","shell.execute_reply":"2025-04-08T02:11:14.089568Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-08T02:11:14.091352Z","iopub.execute_input":"2025-04-08T02:11:14.091752Z","execution_failed":"2025-04-08T02:12:05.538Z"}},"outputs":[],"execution_count":null}]}