SEP- AIA

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 . . .

t

 
  
  4. Write a program to demonstrate K-Means Clustering to group a list of numbers (e.g., [2, 4, 100,
102]) into two clusters.

# 4. Python Program to Demonstrate K-Means Clustering

## Program

```python
# K-Means Clustering

from sklearn.cluster import KMeans

# Hardcoded dataset
numbers = [[2], [4], [100], [102]]

# Create K-Means model with 2 clusters
model = KMeans(n_clusters=2, random_state=0, n_init=10)

# Train the model
model.fit(numbers)

# Get cluster labels
labels = model.labels_

# Display the numbers with their clusters
for i in range(len(numbers)):
    print(numbers[i][0], "belongs to Cluster", labels[i])
```

## Sample Output

```text
2 belongs to Cluster 0
4 belongs to Cluster 0
100 belongs to Cluster 1
102 belongs to Cluster 1
```

*The cluster numbers (0 and 1) may be interchanged.*

## Explanation

* The dataset contains four numbers: **2, 4, 100, and 102**.
* `KMeans(n_clusters=2)` divides the data into **two clusters**.
* The algorithm groups similar values together:

  * **Cluster 1:** 2, 4
  * **Cluster 2:** 100, 102
* `labels_` gives the cluster number assigned to each data point.

Thus, K-Means automatically groups nearby numbers into the same cluster.