How to do KMeans Clustering in Python?

How to do KMeans Clustering in Python?

How to do KMeans Clustering in Python?

This recipe helps you do KMeans Clustering in Python


Recipe Objective

Have you ever tried to use Clustering by K nearest means.

So this recipe is a short example of how we we can do KMeans Clustering in Python.

Step 1 - Import the library

from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans import pandas as pd import seaborn as sns import matplotlib.pyplot as plt

Here we have imported various modules like datasets, KMeans and test_train_split from differnt libraries. We will understand the use of these later while using it in the in the code snipet.
For now just have a look on these imports.

Step 2 - Setup the Data for classifier

Here we have used datasets to load the inbuilt iris dataset and we have created object X and made a dataframe. We have plotted a heat map of correlation between the features. iris = datasets.load_iris() X = data = pd.DataFrame(X) cor = data.corr() fig = plt.figure(figsize=(12,10)); sns.heatmap(cor, square = True);

Step 3 - Model and its Score

Here, First we have used standardscaler to standarise the data such that the mean becomes zero and the standard deviation becomes 1. we are using Kmeans with n_clusters equals to 3 as a Machine Learning model to fit the data. scaler = StandardScaler() X_std = scaler.fit_transform(X) clt = KMeans(n_clusters=3) model = Now we have predicted the output by passing X_std and the clusters. clusters = pd.DataFrame(model.fit_predict(X_std)) data["Cluster"] = clusters Here we have ploted the clusters such that data points of a cluster have the same colour. fig = plt.figure(figsize=(12,10)); ax = fig.add_subplot(111) scatter = ax.scatter(data[0],data[1], c=data["Cluster"],s=50) ax.set_title("KMeans Clustering") ax.set_xlabel("X0"); ax.set_ylabel("X1") plt.colorbar(scatter); Output comes as:

Relevant Projects

Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.

PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Identifying Product Bundles from Sales Data Using R Language
In this data science project in R, we are going to talk about subjective segmentation which is a clustering technique to find out product bundles in sales data.

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

Solving Multiple Classification use cases Using H2O
In this project, we are going to talk about H2O and functionality in terms of building Machine Learning models.