Customer Segmentation Machine Learning Project!
Published: 2023-11-10 20:08:39

Imagine you own a successful supermarket, but you're in the dark about who's buying your products – like whether you have more male or female customers, and who's spending the most. To figure this out, you want to create a smart computer program that can tell you all about your customers. Today you will learn how you can do this.

This project falls under unsupervised machine learning, meaning your computer will figure out customer patterns on its own without you having to label the data. It's like teaching your machine to understand your customers and their habits without explicitly telling it what to look for.

Colab File: https://colab.research.google.com/drive/1l42YN9GiHnpiQ_fLhKrg2mRaHYr7ONsL?usp=sharing

Kaggle dataset: https://www.kaggle.com/datasets/vjchoudhary7/customer-segmentation-tutorial-in-python

**Importing some dependencies:**
first things first, we need some libraries and modules. let me introduce them to you:

**Pandas**: we use it for data analysis and manipulation.
**Numpy**: We handle large datasets with these and do mathematical calculations
**Seaborn**: We visualize our data with this module
**matplotlib.pyplot**: Library for visualization of Python data
**Kmeans**: A machine learning algorithm that is used for grouping data points.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g4wlotcelnf9jtr389p9.png)


**Accessing our customer data:**
To start dealing with our dataset, we first need to access our data. To do this, we use the Python library and a read_csv() function. As the name goes, it reads our CSV file. 
And the .head() function lets us see the tip(top five rows) of our dataset. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1yawa5o7mtpus744c5kq.png)


**Analyzing the data**
Alright, looking good right? now let us see the shape of our data by a function called .shape



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oyf547zq42ymbojkyhp.png)

Great job! 
Let's see if there are any missing values or not. We first find the null values and sum them to analyze the missing values in each column.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/671bvzkg87030j3zasua.png)

**Assigning the data:**
Time to assign the data we will be using. Here this iloc function is used to extract values from the "customer_data" DataFrame, specifically selecting columns at index 3 and 4, and assigns them to the variable "x".
Enjoy the short notes.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckitqjl9ab2to2cizp7o.png)

**Choosing the number of clusters or groups:**
For our model to function effectively, we need to specify the number of customer groups. Selecting too many or too few groups could pose a problem. To determine the appropriate number of groups for our model, we employ a function called WCSS (Within-Cluster-Sum-of-Squares). This function calculates the distance between each data point and its centroid, forming distinct groups based on these distances.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mg6bachfzks4z2gqo5nh.png)



**Visualize the cluster number:**
We can visualize the number of groups by plotting an elbow point graph. This graph helps us identify the optimal number of clusters by observing where the rate of improvement in model performance slows down, resembling an "elbow" in the plot.

You can identify the number of groups by looking at the sudden changes in the graph, like at points 3 and 5. These points indicate potential optimal cluster numbers where the pattern changes significantly, helping us choose the right number of clusters for our analysis.

This code uses the Seaborn (sns) and Matplotlib (plt) libraries to create a line plot. The x-axis represents numbers from 1 to 10 (range(1,11)), and the y-axis shows the values from the "wcss" variable. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tdggj9br6ndbvu27sy7.png)

**Training the k-means clustering model:**
Time to train our model. here we are using KMeans as this project is a clustering project. let me explain my code.

**"n_clusters = 5"** means that we are defining 5 groups.
**"init='k-means++"** is a method used to smartly initialize the cluster centers when applying the KMeans clustering algorithm. The 'k-means++' initialization helps the algorithm converge faster and find better cluster assignments. It's like giving the algorithm a good starting point to make the clustering process more efficient and accurate.

**"random_state = 0"** means that the random aspects of the algorithm will produce the same results every time you run the code. It adds consistency to your machine-learning process.

**Visualizing all the clusters:**
The last step! Lets visualize our clusters. 
Remember that we selected two columns using iloc? we will use this here. Don't get confused, here you can see that one column has all the 0's and another has 1's with every five groups that we set. that
In simpler terms, each line of code is responsible for plotting customers of a specific cluster on a two-dimensional graph, using different colors to distinguish between the clusters. The location of each dot is determined by the values of the first and second features of the customer data (x). This kind of plot helps visualize how customers are grouped into clusters based on the chosen features.

You can see my comment "plotting the centroids". This code draws big black dots on the graph to mark the average positions of each customer group(Centroids). These dots are like the center or heart of each group, showing where most customers in that group are located on the graph.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7xcfaecq0diiybkd250.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9dn6ctk8rmmi6soj8bno.png)


That's it! Congratulations for sticking with this explanation. Those clusters of colored dots represent different customer groups in your supermarket. Each color signifies a distinct group, helping you understand how your customers can be categorized based on certain characteristics.