-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml7
More file actions
43 lines (34 loc) · 1.3 KB
/
ml7
File metadata and controls
43 lines (34 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
# Load the Iris dataset
iris = load_iris()
X = iris.data # The features
y = iris.target # The actual labels (not used in K-means)
# Standardize the data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Initialize the K-Means model
kmeans = KMeans(n_clusters=3, random_state=42)
# Fit the model
kmeans.fit(X_scaled)
# Predict the clusters
y_kmeans = kmeans.predict(X_scaled)
# Get the cluster centers
centers = kmeans.cluster_centers_
# Calculate silhouette score to evaluate the clustering
silhouette_avg = silhouette_score(X_scaled, y_kmeans)
print(f"Silhouette Score: {silhouette_avg:.2f}")
# Visualize the clusters using PCA (Principal Component Analysis for dimensionality reduction)
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_kmeans, cmap='viridis', s=50)
plt.scatter(pca.transform(centers)[:, 0], pca.transform(centers)[:, 1], c='red', s=200, alpha=0.75, label='Centroids')
plt.title('K-Means Clustering on Iris Dataset (PCA-reduced data)')
plt.legend()
plt.show()