You are on page 1of 1

keyboard_arrow_down NAME: PIYUSH VERMA

REGNO: 23MCA1104

# Importing necessary libraries


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

# Load the Iris dataset


iris = datasets.load_iris()
X = iris.data # Features
y = iris.target # Target variable

# Convert to DataFrame
df = pd.DataFrame(X, columns=iris.feature_names)

# Standardize the features


scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Convert back to DataFrame for visualization


df_scaled = pd.DataFrame(X_scaled, columns=iris.feature_names)

# Perform K-means clustering


kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X_scaled)

# Getting cluster centers and labels


cluster_centers = kmeans.cluster_centers_
labels = kmeans.labels_

/usr/local/lib/python3.10/dist-packages/sklearn/cluster/_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to supp
warnings.warn(

 

# Visualizing the clusters


plt.figure(figsize=(10, 6))

# Plotting the clusters


plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels, cmap='viridis', s=50, alpha=0.5)
plt.scatter(cluster_centers[:, 0], cluster_centers[:, 1], c='red', marker='x', s=200, label='Cluster Centers')
plt.title('K-means Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()

output

NOTEBOOK LINK: https://colab.research.google.com/drive/1uR3eRX-M5GkHUnBoukC0VUEMDRhJZeQj?


usp=sharing

You might also like