0% found this document useful (0 votes)
99 views2 pages

KMeans Clustering with Iris Dataset

The document loads the iris dataset and performs k-means clustering on it with 3 clusters. It obtains the cluster labels and plots a scatter plot of the first two features colored by cluster. It also prints the number of instances in each cluster.

Uploaded by

ketan lakum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views2 pages

KMeans Clustering with Iris Dataset

The document loads the iris dataset and performs k-means clustering on it with 3 clusters. It obtains the cluster labels and plots a scatter plot of the first two features colored by cluster. It also prints the number of instances in each cluster.

Uploaded by

ketan lakum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import Numpy,Pandas ,Matplotlib and sklearn Library

import numpy as np
import pandas as pd
import [Link] as plt
from [Link] import KMeans
from [Link] import load_iris

load the IRIS dataset


# Load the iris dataset
iris = load_iris()
X = [Link]

Perform k means clustering


# Perform k-means clustering
kmeans = KMeans(n_clusters=3, random_state=42)
[Link](X)

KMeans(n_clusters=3, random_state=42)

# Get cluster labels


labels = kmeans.labels_
labels

array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1,
1, 1, 1, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 2, 0, 2, 2,
2,
2, 2, 2, 0, 0, 2, 2, 2, 2, 0, 2, 0, 2, 0, 2, 2, 0, 0, 2, 2, 2,
2,
2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 0])

cluster_names = {0: "Setosa", 1: "Versicolor", 2: "Virginica"}


cluster_labels = [cluster_names[label] for label in labels]

Plot the graph to see cluster


[Link](X[:, 0], X[:, 1], c=labels)
[Link]("Sepal Length")
[Link]("Sepal Width")
[Link]("K-means Clustering - Python")
[Link]()
Count the eash cluster instances
cluster_counts = [Link](kmeans.labels_)
for i, count in enumerate(cluster_counts):
print(f"Cluster {i+1}: {count} instances")

Cluster 1: 62 instances
Cluster 2: 50 instances
Cluster 3: 38 instances

You might also like