Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Machine Learning & AI - Lab 3
From raw DataFrames to a K-Means vs. SOM comparison on the Iris dataset
pandasDataFrame indexing, filtering, and selectionK-Means and SOM to real-world data with proper preparationsample_data = {'Name': ['Ahmed','Fatima'], 'Age': [22,21], 'Grade': [85,92]}
df = pd.DataFrame(sample_data)
df.shape # (rows, columns)
df.columns.tolist()
df.dtypesML dataset: 3 species (setosa, versicolor, virginica), 4 featuressklearn.datasets.load_iris() or pd.read_csv()iris = load_iris()
df_iris = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df_iris['species'] = iris.target
df_iris['species_name'] = df_iris['species'].map(
{0: 'setosa', 1: 'versicolor', 2: 'virginica'})150 rows x 6 columnsdf.describe(): count, mean, std, min/max, quartiles per columndf.dtypes and df.isnull().sum(): types and missing-value checkdf['species_name'].value_counts(): 50 samples per species, perfectly balanceddf[['sepal length (cm)', 'sepal width (cm)']]df[df['species_name'] == 'setosa']&filtered = df_iris[(df_iris['species_name'] == 'setosa') &
(df_iris['sepal length (cm)'] > 5.0)]4 to 8 cm vs petal width 0.1 to 2.5 cm)StandardScaler centers on mean 0 and scales to std 1 after transformscaler = StandardScaler()
X_scaled = scaler.fit_transform(X)Sweep k
2 to 10
Track WCSS + Silhouette
at each k
Read the elbow plot
diminishing returns
Choose k = 3
matches true species count
for k in range(2, 11):
km = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=42)
km.fit(X_scaled)
wcss.append(km.inertia_)
silhouette_scores.append(silhouette_score(X_scaled, km.labels_))k=3 on the scaled features, then attach labels back to the DataFramekmeans_final = KMeans(n_clusters=3, init='k-means++', n_init=10, random_state=42)
df_iris['kmeans_cluster'] = kmeans_final.fit_predict(X_scaled)[53, 50, 47], Silhouette Score = 0.459sklearn_som.SOM: a scikit-learn-compatible SOM implementation3x1 for 3 target clusters, 4 input dimensionssom_model = SOM(m=3, n=1, dim=4, lr=0.5, max_iter=1000, random_state=42)
som_model.fit(X_scaled)
df_iris['som_cluster'] = som_model.predict(X_scaled)[70, 30, 50], Silhouette Score = 0.412pd.crosstab(species_name, cluster) shows how well clusters match true species| K-Means | SOM | |
|---|---|---|
| Setosa isolation | Perfect (50/50) | Perfect (50/50) |
| Versicolor / virginica | Some overlap | More overlap |
| Silhouette Score | 0.459 | 0.412 |
groupby('species_name')[cols].mean(): per-group statistics.agg(['mean', 'std', 'min', 'max']): multiple stats at oncesepal_area = length * width, sepal_to_petal_ratiodf_iris['petal_area'] = df_iris['petal length (cm)'] * df_iris['petal width (cm)']| Item | Value |
|---|---|
| Dataset | 150 flowers, 4 features, 3 true species classes |
| Preprocessing | Feature selection + StandardScaler, zero missing values |
| K-Means (k=3) | Silhouette 0.459, best performer |
| SOM (3x1 grid) | Silhouette 0.412 |
K-Means edges out SOM hereDataFrames give powerful, readable tools for real-world data manipulationK-Means and SOM can uncover natural structure in real dataMahmoud Abas|Lab 3: Data Preprocessing and Clustering with Real-World Data using Pandas DataFrames