{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":91498,"databundleVersionId":11655853,"sourceType":"competition"}],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# We will cover :\n\n* Goal of ComeptitionAbout\n* Data Set given\n* Approach to DataSet and Guide to Train ML ( including import topics you must known )\n* Data Visulization including 3D\n* Discriptive and Infrential Statistiscs\n\n\n# **A. Goal of the Competition ------------------>**","metadata":{}},{"cell_type":"markdown","source":"![https://firebasestorage.googleapis.com/v0/b/heaven-on-this-e-1673398261366.appspot.com/o/ChatGPT%20Image%20May%209%2C%202025%2C%2010_19_11%20AM.png?alt=media&token=a698f3da-0ea9-4dd1-a9ee-d3e1aad03ebf](https://firebasestorage.googleapis.com/v0/b/heaven-on-this-e-1673398261366.appspot.com/o/ChatGPT%20Image%20May%209%2C%202025%2C%2010_19_11%20AM.png?alt=media&token=a698f3da-0ea9-4dd1-a9ee-d3e1aad03ebf)","metadata":{}},{"cell_type":"markdown","source":"This is **computer vision** competition focused image matching. The goal is to develop algorithms that can accurately match and reconstruct 3D scenes from a collection of 2D images taken from different viewpoints.","metadata":{}},{"cell_type":"markdown","source":"In Short, **Participants must build models that can match keypoints across multiple images of the same scene and estimate camera poses (position & orientation).**","metadata":{}},{"cell_type":"markdown","source":"**Real World Application :**","metadata":{}},{"cell_type":"markdown","source":"\n1. Advances in this field improve 3D scanning, AR/VR, autonomous navigation, and drone mapping.\n2. The challenge pushes the boundaries of structure-from-motion (SfM) and multi-view geometry.\n","metadata":{}},{"cell_type":"markdown","source":"# **B. About the DataSet------------------>**","metadata":{}},{"cell_type":"markdown","source":"The Dataset contains 2 Folders and 3 Files.","metadata":{}},{"cell_type":"markdown","source":"## 1. test Folder","metadata":{}},{"cell_type":"markdown","source":"The Test Folder Conatins 2/13 Images which could be used to Test Data on Model that is trained. It contains ETs ( Extra Terristrial ) containing 22 Images and Stairs which have 51 files. ","metadata":{}},{"cell_type":"markdown","source":"## 2. train Folder","metadata":{}},{"cell_type":"markdown","source":"This folder contains 13 Folders each of Extra Terristrial, Army_garden, Vineyard, etc....each having Image under it. This image path is referenced in train_label.csv","metadata":{}},{"cell_type":"markdown","source":"## 3. sample_submission.csv","metadata":{}},{"cell_type":"markdown","source":"The sample_submission is the csv demo file on how your submission should be . It must first conatins the image ID that is tested, than the predicted Image Category ( like ET, garden, army) put under \"dataset\" column, than the \"scene\" which will contain the image matching scene ( you must match similar angle photo scenes together )\n\nThan there's \"image\" column containing file name of image. The \"rotation_matrix\" is the predicted Rotation of Image and the \"translation_vector\" contains the Predicted 3d Vector of image in 3d coordinates seperated by \";\"","metadata":{}},{"cell_type":"markdown","source":"## 4. train_label.csv","metadata":{}},{"cell_type":"markdown","source":"It contains 5 Column, one of \"dataset\" contaims name of image, \"scene\" showing the particular scene ( fountain, bike, chairs ....), \"image\" showing the **Real Image Name** of image being studied, and \"rotation_matrix\" containing the Rotation of Image and than \"translation_matrix\" containing 3d position in 3D coordinates seperated by \";\"","metadata":{}},{"cell_type":"markdown","source":"## 5. train_thresholds.csv\n\nIt contains all the dataset thresholds. Thresholds is important as it ensures that only keypoints with confidence scores above the threshold are considered, which helps reduce noise and focus on reliable keypoints.\nIt have 3 columns, one for \"dataset\" which shows Category, \"scene\" means Object Name and \"thresholds\" containing All thresholds ","metadata":{}},{"cell_type":"markdown","source":"# **C. Approach to DataSet ---------------------->**","metadata":{}},{"cell_type":"markdown","source":"or WINNING this Competition, you need to first master Important Topics required to understand the Model Problem needed here, particular steps to be followed, and Fine Tuning Model using Ensemblem or Optimization.\n\n> We assume you known Fundamentals like Pandas, Supervised Learning, etc","metadata":{}},{"cell_type":"markdown","source":"## 1. Important Topics you should known","metadata":{}},{"cell_type":"markdown","source":"\n1. Brute-Force Matcher, FLANN (OpenCV)\n2. Ratio Test (Lowe’s method)\n3. SuperGlue (graph neural network for matching)\n4. LoFTR (detector-free, good for low-texture scenes)\n5. LightGlue (faster alternative to SuperGlue)\n\n\nCamera Pose Estimation\n\n1. Fundamental Matrix (cv2.findFundamentalMat)\n2. Essential Matrix (cv2.recoverPose)\n\n\nPnP (Perspective-n-Point)\n\n1. cv2.solvePnPRansac (robust pose estimation)\n2. 3D Reconstruction & OptimizationTriangulation (from multiple views)\n3. Bundle Adjustment (non-linear optimization)\n4. Depth Estimation (Multi-View Stereo - MVS)\n\n\nAdvanced Topics (For Top Rankings)\n\n1. Transformer-based Matching (e.g., LoFTR)\n2. Test-Time Augmentation (TTA) (flip, rotate images)\n3. Efficient RANSAC (speed vs. accuracy tradeoff)\n4. Hybrid Approaches (e.g., SuperPoint + LightGlue + COLMAP)\n","metadata":{}},{"cell_type":"markdown","source":"## 2. Approach","metadata":{}},{"cell_type":"markdown","source":"To compete in the Image Matching Challenge 2025, you need to process the dataset, extract useful features from the images, and utilize the rotation and translation matrices for scene understanding","metadata":{}},{"cell_type":"markdown","source":">> WE ARE STILL WORKING on the demo code       !!!!!!!!Thanks for Waiting !!!!","metadata":{}},{"cell_type":"markdown","source":"## 3. Checklist for Success\n\n1. ✅ Week 1: Learn OpenCV (SIFT, RANSAC, PnP).\n2. ✅ Week 2: Implement SuperPoint + SuperGlue pipeline.\n3. ✅ Week 3: Integrate COLMAP for 3D reconstruction.\n4. ✅ Week 4: Optimize speed & accuracy (LoFTR, LightGlue).\n5. ✅ Final Week: Ensemble models + test-time augmentation.\n","metadata":{}},{"cell_type":"markdown","source":"## 4. Helpful Resources","metadata":{}},{"cell_type":"markdown","source":"COLMAP Tutorial: https://colmap.github.io/\n\nSuperPoint + SuperGlue: GitHub - MagicLeap/SuperGlue\n\nLoFTR Paper: https://zju3dv.github.io/loftr/","metadata":{}},{"cell_type":"markdown","source":"# **D. Visualize Data------------------>**","metadata":{}},{"cell_type":"code","source":"# Install \nimport subprocess\nimport sys\n\ndef silent_install(packages):\n    subprocess.run(\n        [sys.executable, \"-m\", \"pip\", \"install\", \"-q\"] + packages,\n        stdout=subprocess.DEVNULL,\n        stderr=subprocess.DEVNULL,\n    )\n\nrequired_packages = [\n    \"open3d\",\n    \"pycolmap\",\n    \"numpy\",\n    \"torch\",\n    \"torchvision\",\n    \"opencv-python\",\n    \"timm\"\n]\n\n# Install silently\nsilent_install(required_packages)\n\n# Verify \ntry:\n    import open3d, pycolmap, torch, cv2, timm\n    print(\"✅ All packages installed successfully!\")\nexcept ImportError as e:\n    print(f\"❌ Error: {e}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:27:44.807827Z","iopub.execute_input":"2025-05-09T05:27:44.808146Z","iopub.status.idle":"2025-05-09T05:29:41.904177Z","shell.execute_reply.started":"2025-05-09T05:27:44.808120Z","shell.execute_reply":"2025-05-09T05:29:41.903530Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 1. Visualize Keypoints (Single Image)","metadata":{}},{"cell_type":"markdown","source":"Use OpenCV to plot detected keypoints (e.g., SIFT/SuperPoint) important in Image Matching","metadata":{}},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\n\n# Detect keypoints\nsift = cv2.SIFT_create()\nimg=cv2.imread(\"/kaggle/input/image-matching-challenge-2025/train/ETs/another_et_another_et001.png\")\nkp = sift.detect(img, None)\n\n# Draw keypoints\nimg_kp = cv2.drawKeypoints(img, kp, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\nplt.imshow(img_kp)\nplt.title(f\"SIFT Keypoints: {len(kp)}\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:41.905255Z","iopub.execute_input":"2025-05-09T05:29:41.905475Z","iopub.status.idle":"2025-05-09T05:29:42.368190Z","shell.execute_reply.started":"2025-05-09T05:29:41.905458Z","shell.execute_reply":"2025-05-09T05:29:42.367557Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. Visualize Matches (Between Two Images)","metadata":{}},{"cell_type":"markdown","source":"Plot feature matches using cv2.drawMatches. You could see Alien many features are Matching.","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimg1 = cv2.imread(\"/kaggle/input/image-matching-challenge-2025/train/ETs/another_et_another_et001.png\", cv2.IMREAD_GRAYSCALE)\nimg2 = cv2.imread(\"/kaggle/input/image-matching-challenge-2025/train/ETs/another_et_another_et005.png\", cv2.IMREAD_GRAYSCALE)\n\n\ndetector = cv2.ORB_create()  # or cv2.SIFT_create()\n\n\nkp1, desc1 = detector.detectAndCompute(img1, None)\nkp2, desc2 = detector.detectAndCompute(img2, None)\n\n\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)  # For ORB\nmatches = bf.match(desc1, desc2)\nmatches = sorted(matches, key=lambda x: x.distance)[:50]  # Top 50 matches\n\n\nimg_matches = cv2.drawMatches(\n    img1, kp1, img2, kp2, matches, None,\n    flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS\n)\n\n\nplt.figure(figsize=(20, 10))\nplt.imshow(cv2.cvtColor(img_matches, cv2.COLOR_BGR2RGB))\nplt.title(\"Top 50 Feature Matches\")\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:42.369039Z","iopub.execute_input":"2025-05-09T05:29:42.369278Z","iopub.status.idle":"2025-05-09T05:29:43.158548Z","shell.execute_reply.started":"2025-05-09T05:29:42.369259Z","shell.execute_reply":"2025-05-09T05:29:43.157941Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Visualize Epipolar Lines (Geometry Check)","metadata":{}},{"cell_type":"markdown","source":"Validate Fundamental Matrix by drawing epipolar lines.","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimg1 = cv2.imread('/kaggle/input/image-matching-challenge-2025/train/ETs/another_et_another_et001.png', cv2.IMREAD_GRAYSCALE)\nimg2 = cv2.imread('/kaggle/input/image-matching-challenge-2025/train/ETs/another_et_another_et002.png', cv2.IMREAD_GRAYSCALE)\n\n\nassert img1 is not None and img2 is not None, \"Error loading images\"\n\n\nsift = cv2.SIFT_create()\nkp1, desc1 = sift.detectAndCompute(img1, None)\nkp2, desc2 = sift.detectAndCompute(img2, None)\n\n\nbf = cv2.BFMatcher()\nmatches = bf.match(desc1, desc2)\nmatches = sorted(matches, key=lambda x: x.distance)[:50]  # Top 50 matches\n\n\npts1 = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)\npts2 = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)\n\n\nF, mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_RANSAC)\n\n\ndef draw_epilines(img1, img2, pts1, pts2, F):\n    # Convert to color for visualization\n    img1_color = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)\n    img2_color = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)\n    \n    lines1 = cv2.computeCorrespondEpilines(pts2.reshape(-1, 1, 2), 2, F)\n    lines1 = lines1.reshape(-1, 3)\n    \n    for r, pt1, pt2 in zip(lines1, pts1, pts2):\n        color = tuple(np.random.randint(0, 255, 3).tolist())\n        \n        # Draw epipolar line on img1\n        x0, y0 = map(int, [0, -r[2]/r[1]])\n        x1, y1 = map(int, [img1.shape[1], -(r[2] + r[0]*img1.shape[1])/r[1]])\n        cv2.line(img1_color, (x0, y0), (x1, y1), color, 1)\n        \n        \n        pt2_int = (int(pt2[0][0]), int(pt2[0][1])) \n        cv2.circle(img2_color, pt2_int, 5, color, -1)\n    \n    return img1_color, img2_color\n\n# 7. Generate and display results\nimg1_epi, img2_epi = draw_epilines(img1, img2, pts1, pts2, F)\n\nplt.figure(figsize=(12, 6))\nplt.subplot(121); plt.imshow(cv2.cvtColor(img1_epi, cv2.COLOR_BGR2RGB)); plt.title(\"Epipolar Lines (Image 1)\")\nplt.subplot(122); plt.imshow(cv2.cvtColor(img2_epi, cv2.COLOR_BGR2RGB)); plt.title(\"Image 2 with Keypoints\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:43.159356Z","iopub.execute_input":"2025-05-09T05:29:43.159657Z","iopub.status.idle":"2025-05-09T05:29:43.764652Z","shell.execute_reply.started":"2025-05-09T05:29:43.159628Z","shell.execute_reply":"2025-05-09T05:29:43.764024Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Visualize 3D Point Cloud (COLMAP Output)","metadata":{}},{"cell_type":"markdown","source":"Plot 3D reconstructed points using open3d","metadata":{}},{"cell_type":"markdown","source":"# **E. Statsitics**","metadata":{}},{"cell_type":"markdown","source":"# Descriptive Statistics","metadata":{}},{"cell_type":"markdown","source":"## 1. Loading Data","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import f_oneway, pearsonr\n\n\ntrain_df = pd.read_csv(\"/kaggle/input/image-matching-challenge-2025/train_labels.csv\")\nthreshold_df = pd.read_csv(\"/kaggle/input/image-matching-challenge-2025/train_thresholds.csv\")\n\n\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:43.766455Z","iopub.execute_input":"2025-05-09T05:29:43.766659Z","iopub.status.idle":"2025-05-09T05:29:44.026519Z","shell.execute_reply.started":"2025-05-09T05:29:43.766644Z","shell.execute_reply":"2025-05-09T05:29:44.025781Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. Scene distribution","metadata":{}},{"cell_type":"code","source":"\nscene_counts = train_df['scene'].value_counts()\nprint(\"Scene Distribution:\")\nprint(scene_counts)\n\n\nplt.figure(figsize=(10, 6))\nscene_counts.plot(kind='bar', color='skyblue')\nplt.title(\"Number of Images per Scene\")\nplt.xlabel(\"Scene\")\nplt.ylabel(\"Count\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.027284Z","iopub.execute_input":"2025-05-09T05:29:44.027905Z","iopub.status.idle":"2025-05-09T05:29:44.363656Z","shell.execute_reply.started":"2025-05-09T05:29:44.027878Z","shell.execute_reply":"2025-05-09T05:29:44.362937Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Extract and summarize rotation matrices and translation vectors","metadata":{}},{"cell_type":"code","source":"\ndef parse_matrix(matrix_str):\n    return np.array([float(x) for x in matrix_str.split(\";\")]).reshape(3, 3)\n\ndef parse_vector(vector_str):\n    return np.array([float(x) for x in vector_str.split(\";\")])\n\ntrain_df['rotation_magnitude'] = train_df['rotation_matrix'].apply(lambda x: np.linalg.norm(parse_matrix(x)))\ntrain_df['translation_magnitude'] = train_df['translation_vector'].apply(lambda x: np.linalg.norm(parse_vector(x)))\n\n# Summary of transformations\nprint(\"\\nSummary of Rotation and Translation Magnitudes:\")\nprint(train_df[['rotation_magnitude', 'translation_magnitude']].describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.364316Z","iopub.execute_input":"2025-05-09T05:29:44.364492Z","iopub.status.idle":"2025-05-09T05:29:44.414069Z","shell.execute_reply.started":"2025-05-09T05:29:44.364477Z","shell.execute_reply":"2025-05-09T05:29:44.413406Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Plot distribution of translation magnitudes","metadata":{}},{"cell_type":"code","source":"\nplt.figure(figsize=(8, 6))\nsns.histplot(train_df['translation_magnitude'], kde=True, bins=20)\nplt.title(\"Distribution of Translation Magnitudes\")\nplt.xlabel(\"Translation Magnitude\")\nplt.ylabel(\"Frequency\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.414774Z","iopub.execute_input":"2025-05-09T05:29:44.415035Z","iopub.status.idle":"2025-05-09T05:29:44.656382Z","shell.execute_reply.started":"2025-05-09T05:29:44.415017Z","shell.execute_reply":"2025-05-09T05:29:44.655783Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5. Threshold distribution","metadata":{}},{"cell_type":"code","source":"\nplt.figure(figsize=(8, 6))\nsns.histplot(threshold_df['thresholds'], kde=True, bins=20)\nplt.title(\"Distribution of Thresholds\")\nplt.xlabel(\"Threshold\")\nplt.ylabel(\"Frequency\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.657091Z","iopub.execute_input":"2025-05-09T05:29:44.657344Z","iopub.status.idle":"2025-05-09T05:29:44.849397Z","shell.execute_reply.started":"2025-05-09T05:29:44.657326Z","shell.execute_reply":"2025-05-09T05:29:44.848671Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Inferential Statistics","metadata":{}},{"cell_type":"markdown","source":"## 6. Hypothesis Testing: Do transformation magnitudes vary across scenes?","metadata":{}},{"cell_type":"code","source":"\n\n\nscenes = train_df['scene'].unique()\nrotation_by_scene = [train_df[train_df['scene'] == scene]['rotation_magnitude'] for scene in scenes]\ntranslation_by_scene = [train_df[train_df['scene'] == scene]['translation_magnitude'] for scene in scenes]\n\n# ANOVA for rotation magnitude\nf_stat_rot, p_value_rot = f_oneway(*rotation_by_scene)\nprint(\"\\nANOVA Test for Rotation Magnitudes:\")\nprint(f\"F-statistic: {f_stat_rot}, P-value: {p_value_rot}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.850060Z","iopub.execute_input":"2025-05-09T05:29:44.850357Z","iopub.status.idle":"2025-05-09T05:29:44.887625Z","shell.execute_reply.started":"2025-05-09T05:29:44.850341Z","shell.execute_reply":"2025-05-09T05:29:44.886969Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 7. ANOVA for translation magnitude","metadata":{}},{"cell_type":"code","source":"\nf_stat_trans, p_value_trans = f_oneway(*translation_by_scene)\nprint(\"\\nANOVA Test for Translation Magnitudes:\")\nprint(f\"F-statistic: {f_stat_trans}, P-value: {p_value_trans}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.888350Z","iopub.execute_input":"2025-05-09T05:29:44.888578Z","iopub.status.idle":"2025-05-09T05:29:44.895971Z","shell.execute_reply.started":"2025-05-09T05:29:44.888561Z","shell.execute_reply":"2025-05-09T05:29:44.895233Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 8. Correlation between rotation and translation magnitudes","metadata":{}},{"cell_type":"code","source":"\ncorrelation, p_value_corr = pearsonr(train_df['rotation_magnitude'], train_df['translation_magnitude'])\nprint(\"\\nCorrelation Analysis:\")\nprint(f\"Pearson Correlation: {correlation}, P-value: {p_value_corr}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.896694Z","iopub.execute_input":"2025-05-09T05:29:44.896950Z","iopub.status.idle":"2025-05-09T05:29:44.916685Z","shell.execute_reply.started":"2025-05-09T05:29:44.896935Z","shell.execute_reply":"2025-05-09T05:29:44.915979Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 9. Cooefficient & Intercept","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nimport pandas as pd\n\n\nmerged_df = pd.merge(train_df, threshold_df, on=\"scene\")\n\n\ndef extract_first_number(value):\n    if isinstance(value, str):\n        # Handle string values (e.g., \"1.2;3.4\" -> 1.2)\n        return float(value.split(\";\")[0])\n    elif isinstance(value, (int, float)):\n        # Already numeric\n        return float(value)\n    else:\n        raise ValueError(f\"Unexpected value type: {type(value)}\")\n\n\nX = np.column_stack([\n    merged_df['rotation_magnitude'].apply(extract_first_number),\n    merged_df['translation_magnitude'].apply(extract_first_number)\n])\ny = merged_df['thresholds'].apply(extract_first_number)\n\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, \n    test_size=0.2, \n    random_state=42\n)\n\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\nr_squared = regressor.score(X_test, y_test)\nprint(\"\\nRegression Analysis:\")\nprint(f\"R-squared: {r_squared:.4f}\")\nprint(\"Coefficients:\", regressor.coef_)\nprint(\"Intercept:\", regressor.intercept_)\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.917441Z","iopub.execute_input":"2025-05-09T05:29:44.917784Z","iopub.status.idle":"2025-05-09T05:29:44.957282Z","shell.execute_reply.started":"2025-05-09T05:29:44.917736Z","shell.execute_reply":"2025-05-09T05:29:44.956769Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#just Predicting ......\ny_pred = regressor.predict(X_test)\nprint(y_pred)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-09T05:29:44.959042Z","iopub.execute_input":"2025-05-09T05:29:44.959593Z","iopub.status.idle":"2025-05-09T05:29:44.965454Z","shell.execute_reply.started":"2025-05-09T05:29:44.959576Z","shell.execute_reply":"2025-05-09T05:29:44.964776Z"}},"outputs":[],"execution_count":null}]}