{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "594efd0d-0c6b-4cf8-a2f5-bde0eb974174",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6836d7f7-811f-4aa9-b31c-49b6e6b3821f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['num_links', 'num_words', 'has_offer', 'sender_score', 'all_caps',\n",
      "       'is_spam'],\n",
      "      dtype='object')\n",
      "   num_links  num_words  has_offer  sender_score  all_caps  is_spam\n",
      "0          3         98          1      0.718607         0        0\n",
      "1          0        170          0      0.698901         1        0\n",
      "2          0         38          0      0.620466         0        0\n",
      "3          0        116          0      0.701755         0        0\n",
      "4          3         89          1      0.583621         1        1\n"
     ]
    }
   ],
   "source": [
    "df = pd.read_csv(\"spam_detection_dataset.csv\", encoding=\"ISO-8859-1\")  # Adjust path if needed\n",
    "\n",
    "# Print basic info\n",
    "print(df.columns)\n",
    "print(df.head(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "32722793-45d2-4241-97b8-317ed5a1a9d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "if \"Email No.\" in df.columns:\n",
    "    df = df.drop(columns=[\"Email No.\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2835047c-966b-4168-960a-bb7796651342",
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"is_spam\"] = df[\"is_spam\"].astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "681664d5-98e6-4b1b-b064-ae4f15f762eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Features & target\n",
    "X = df.drop(columns=[\"is_spam\"])\n",
    "y = df[\"is_spam\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "64fd4602-ab4e-47fb-a65c-a69a5f709814",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.2, random_state=42, stratify=y\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f30ca926-d4f2-4c46-b01c-30ccfa4c00ad",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- KNN Performance ---\n",
      "Accuracy: 0.9425\n",
      "Classification Report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           0       0.95      0.99      0.97      3633\n",
      "           1       0.86      0.44      0.59       367\n",
      "\n",
      "    accuracy                           0.94      4000\n",
      "   macro avg       0.90      0.72      0.78      4000\n",
      "weighted avg       0.94      0.94      0.93      4000\n",
      "\n",
      "Confusion Matrix:\n",
      " [[3607   26]\n",
      " [ 204  163]]\n"
     ]
    }
   ],
   "source": [
    "knn = KNeighborsClassifier(n_neighbors=5)\n",
    "knn.fit(X_train, y_train)\n",
    "y_pred_knn = knn.predict(X_test)\n",
    "\n",
    "print(\"\\n--- KNN Performance ---\")\n",
    "print(\"Accuracy:\", accuracy_score(y_test, y_pred_knn))\n",
    "print(\"Classification Report:\\n\", classification_report(y_test, y_pred_knn))\n",
    "print(\"Confusion Matrix:\\n\", confusion_matrix(y_test, y_pred_knn))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f28d2fef-2655-4ebe-b820-b3c6cb37a034",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- SVM Performance ---\n",
      "Accuracy: 0.93875\n",
      "Classification Report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           0       0.95      0.98      0.97      3633\n",
      "           1       0.75      0.50      0.60       367\n",
      "\n",
      "    accuracy                           0.94      4000\n",
      "   macro avg       0.85      0.74      0.78      4000\n",
      "weighted avg       0.93      0.94      0.93      4000\n",
      "\n",
      "Confusion Matrix:\n",
      " [[3573   60]\n",
      " [ 185  182]]\n"
     ]
    }
   ],
   "source": [
    "svm = SVC(kernel='linear', random_state=42)  # Linear kernel for binary classification\n",
    "svm.fit(X_train, y_train)\n",
    "y_pred_svm = svm.predict(X_test)\n",
    "\n",
    "print(\"\\n--- SVM Performance ---\")\n",
    "print(\"Accuracy:\", accuracy_score(y_test, y_pred_svm))\n",
    "print(\"Classification Report:\\n\", classification_report(y_test, y_pred_svm))\n",
    "print(\"Confusion Matrix:\\n\", confusion_matrix(y_test, y_pred_svm))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "82c5530e-421f-4ecd-8f2b-8cc6c46d2ca9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 37856 characters]",
      "text/plain": [
       "<Figure size 1200x500 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(1, 2, figsize=(12, 5))\n",
    "\n",
    "sns.heatmap(confusion_matrix(y_test, y_pred_knn), annot=True, fmt=\"d\", cmap=\"Blues\", ax=ax[0])\n",
    "ax[0].set_title(\"KNN Confusion Matrix\")\n",
    "ax[0].set_xlabel(\"Predicted\")\n",
    "ax[0].set_ylabel(\"Actual\")\n",
    "\n",
    "sns.heatmap(confusion_matrix(y_test, y_pred_svm), annot=True, fmt=\"d\", cmap=\"Greens\", ax=ax[1])\n",
    "ax[1].set_title(\"SVM Confusion Matrix\")\n",
    "ax[1].set_xlabel(\"Predicted\")\n",
    "ax[1].set_ylabel(\"Actual\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "badf88e8-a41f-4586-af07-e08b4bbf29b8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
