{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "61342b32-ec46-4de2-a03d-feb1ef8646a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.cluster import KMeans\n",
    "from scipy.cluster.hierarchy import linkage, dendrogram, fcluster\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3210b6d2-d1cb-4c1e-9476-6fca6558faf4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset shape: (2823, 25)\n",
      "   ORDERNUMBER  QUANTITYORDERED  PRICEEACH  ORDERLINENUMBER    SALES  \\\n",
      "0        10107               30      95.70                2  2871.00   \n",
      "1        10121               34      81.35                5  2765.90   \n",
      "2        10134               41      94.74                2  3884.34   \n",
      "3        10145               45      83.26                6  3746.70   \n",
      "4        10159               49     100.00               14  5205.27   \n",
      "\n",
      "         ORDERDATE   STATUS  QTR_ID  MONTH_ID  YEAR_ID  ...  \\\n",
      "0   2/24/2003 0:00  Shipped       1         2     2003  ...   \n",
      "1    5/7/2003 0:00  Shipped       2         5     2003  ...   \n",
      "2    7/1/2003 0:00  Shipped       3         7     2003  ...   \n",
      "3   8/25/2003 0:00  Shipped       3         8     2003  ...   \n",
      "4  10/10/2003 0:00  Shipped       4        10     2003  ...   \n",
      "\n",
      "                    ADDRESSLINE1  ADDRESSLINE2           CITY STATE  \\\n",
      "0        897 Long Airport Avenue           NaN            NYC    NY   \n",
      "1             59 rue de l'Abbaye           NaN          Reims   NaN   \n",
      "2  27 rue du Colonel Pierre Avia           NaN          Paris   NaN   \n",
      "3             78934 Hillside Dr.           NaN       Pasadena    CA   \n",
      "4                7734 Strong St.           NaN  San Francisco    CA   \n",
      "\n",
      "  POSTALCODE COUNTRY TERRITORY CONTACTLASTNAME CONTACTFIRSTNAME DEALSIZE  \n",
      "0      10022     USA       NaN              Yu             Kwai    Small  \n",
      "1      51100  France      EMEA         Henriot             Paul    Small  \n",
      "2      75508  France      EMEA        Da Cunha           Daniel   Medium  \n",
      "3      90003     USA       NaN           Young            Julie   Medium  \n",
      "4        NaN     USA       NaN           Brown            Julie   Medium  \n",
      "\n",
      "[5 rows x 25 columns]\n"
     ]
    }
   ],
   "source": [
    "df = pd.read_csv(\"sales_data_sample.csv\", encoding='latin1', on_bad_lines='skip')\n",
    "print(\"Dataset shape:\", df.shape)\n",
    "print(df.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "21cc8252-3eaa-467a-b669-955b44d3a551",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Features used for clustering:\n",
      "    ORDERNUMBER  QUANTITYORDERED  PRICEEACH  ORDERLINENUMBER    SALES  QTR_ID  \\\n",
      "0        10107               30      95.70                2  2871.00       1   \n",
      "1        10121               34      81.35                5  2765.90       2   \n",
      "2        10134               41      94.74                2  3884.34       3   \n",
      "3        10145               45      83.26                6  3746.70       3   \n",
      "4        10159               49     100.00               14  5205.27       4   \n",
      "\n",
      "   MONTH_ID  YEAR_ID  MSRP  \n",
      "0         2     2003    95  \n",
      "1         5     2003    95  \n",
      "2         7     2003    95  \n",
      "3         8     2003    95  \n",
      "4        10     2003    95  \n"
     ]
    }
   ],
   "source": [
    "X = df.select_dtypes(include=['int64', 'float64'])\n",
    "print(\"Features used for clustering:\\n\", X.head())\n",
    "\n",
    "# Select relevant numeric columns\n",
    "# X = df[['SALES', 'QUANTITYORDERED', 'PRICEEACH']]\n",
    "\n",
    "# Handle missing values if any\n",
    "# X = features.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "50cfbd98-19dd-4e27-9708-6890c3a1f774",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler = StandardScaler()\n",
    "X_scaled = scaler.fit_transform(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5658a300-be94-444f-892e-1ede2171f671",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 37556 characters]",
      "text/plain": [
       "<Figure size 600x400 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 117048 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "K-Means Cluster Centers:\n",
      " [[ 0.80842073  0.15626173  0.1599169  -0.10322049  0.13943053 -1.15351152\n",
      "  -1.15675151  1.18412804  0.07164397]\n",
      " [-0.26408187  0.0398995   0.70503285  0.01560294  0.53444299  0.50961433\n",
      "   0.5069744  -0.44559165  0.62315027]\n",
      " [-0.30770787 -0.1781969  -1.04941352  0.06293662 -0.81019145  0.26569688\n",
      "   0.2717579  -0.3739815  -0.87128259]]\n",
      "\n",
      "Cluster counts:\n",
      " KMeans_Cluster\n",
      "1    1183\n",
      "2     907\n",
      "0     733\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# Determine optimal number of clusters using Elbow Method\n",
    "wcss = []\n",
    "for k in range(1, 11):\n",
    "    kmeans = KMeans(n_clusters=k, random_state=42)\n",
    "    kmeans.fit(X_scaled)\n",
    "    wcss.append(kmeans.inertia_)\n",
    "\n",
    "# Plot Elbow Method\n",
    "plt.figure(figsize=(6,4))\n",
    "plt.plot(range(1, 11), wcss, marker='o')\n",
    "plt.title('Elbow Method')\n",
    "plt.xlabel('Number of clusters (k)')\n",
    "plt.ylabel('Inertia (WCSS)')\n",
    "plt.show()\n",
    "\n",
    "# Fit KMeans with chosen number of clusters (example: 3 clusters)\n",
    "kmeans = KMeans(n_clusters=3, random_state=42) # Add n_init=10 param in the function to suppress warnings\n",
    "clusters_kmeans = kmeans.fit_predict(X_scaled)\n",
    "df['KMeans_Cluster'] = clusters_kmeans\n",
    "\n",
    "# Visualize clusters\n",
    "sns.scatterplot(x='SALES', y='PRICEEACH', hue='KMeans_Cluster', data=df, palette='viridis')\n",
    "plt.title(\"K-Means Clustering\")\n",
    "plt.show()\n",
    "\n",
    "print(\"\\nK-Means Cluster Centers:\\n\", kmeans.cluster_centers_)\n",
    "print(\"\\nCluster counts:\\n\", df['KMeans_Cluster'].value_counts())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e138c835-9f67-46a0-9716-dedec10c5470",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 49952 characters]",
      "text/plain": [
       "<Figure size 1000x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Hierarchical Cluster counts:\n",
      " 1    1655\n",
      "3     690\n",
      "2     478\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# Create linkage matrix\n",
    "Z = linkage(X_scaled, method='ward')\n",
    "\n",
    "# Plot dendrogram\n",
    "plt.figure(figsize=(10,5))\n",
    "dendrogram(Z)\n",
    "plt.title('Hierarchical Clustering Dendrogram')\n",
    "plt.xlabel('Samples')\n",
    "plt.ylabel('Distance')\n",
    "plt.show()\n",
    "\n",
    "# Assign clusters (example: 3 clusters)\n",
    "clusters_hier = fcluster(Z, t=3, criterion='maxclust')\n",
    "df['Hierarchical_Cluster'] = clusters_hier\n",
    "\n",
    "print(\"\\nHierarchical Cluster counts:\\n\", pd.Series(clusters_hier).value_counts())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc9779fa-1fcd-4768-8fea-ee89f9366c82",
   "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
}
