File size: 5,046 Bytes
3ce1780
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37c04
 
7aac781
 
4d37c04
 
 
 
 
 
 
 
 
 
 
7b6e87d
 
 
 
 
 
 
 
 
4d37c04
 
 
 
 
 
 
 
 
7b6e87d
 
 
 
 
 
 
 
 
 
 
 
4d37c04
 
 
 
7b6e87d
4d37c04
7b6e87d
4d37c04
 
 
 
 
 
 
 
 
 
 
 
7b6e87d
 
 
 
4d37c04
7b6e87d
4d37c04
 
 
 
7b6e87d
 
4d37c04
 
 
7b6e87d
 
 
 
 
4d37c04
7b6e87d
4d37c04
 
7b6e87d
4d37c04
7b6e87d
4d37c04
7b6e87d
4d37c04
7b6e87d
 
 
 
4d37c04
7b6e87d
 
 
 
 
4d37c04
7b6e87d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37c04
 
 
 
 
 
 
7b6e87d
4d37c04
7b6e87d
4d37c04
 
 
 
 
 
 
7aac781
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
---
license: cc-by-4.0
task_categories:
  - image-classification
  - image-feature-extraction
tags:
  - ipl
  - cricket
  - sports
  - image-dataset
size_categories:
  - n<1K
---

# IITB PML Semester 1 — IPL Image Dataset

> **Dataset on Hugging Face:** [goyaljai/IITB-PML-SEM1](https://huggingface.co/datasets/goyaljai/IITB-PML-SEM1)

963 IPL cricket images, uniformly processed to **800 × 600 px JPEG**, prepared for the Practical Machine Learning course, Semester 1, IIT Bombay.

## Dataset Details

| Property | Value |
|---|---|
| Total images | 963 |
| Format | JPEG |
| Dimensions | 800 × 600 px (all uniform) |
| Size | ~141 MB |

### Train / Test Split

| Split | Folder | Count | % |
|---|---|---|---|
| Train | `train/` | 674 | 70% |
| Test | `test/` | 289 | 30% |

> Split is random with `seed=42` for reproducibility.


---

## How to Load

```python
from huggingface_hub import snapshot_download
from pathlib import Path

# Download full dataset
dataset_dir = Path(snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset"))

# Train and test paths
train_dir = dataset_dir / "train"
test_dir  = dataset_dir / "test"

train_images = sorted(train_dir.glob("*.jpg"))
test_images  = sorted(test_dir.glob("*.jpg"))

print(f"Train: {len(train_images)} images")
print(f"Test : {len(test_images)} images")
```

---

## Example: K-Means Clustering on Train Set, Evaluate on Test Set

Cluster IPL images by colour histogram features. Fit KMeans on the train split, then assign test images to the nearest cluster.

```python
from huggingface_hub import snapshot_download
from pathlib import Path
from PIL import Image
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import normalize
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# ── 1. Download dataset ──────────────────────────────────────────────────────
dataset_dir = Path(snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset"))
train_images = sorted((dataset_dir / "train").glob("*.jpg"))
test_images  = sorted((dataset_dir / "test").glob("*.jpg"))
print(f"Train: {len(train_images)} | Test: {len(test_images)}")

# ── 2. Feature extraction (colour histogram) ─────────────────────────────────
def extract_histogram(path, bins=32):
    img = Image.open(path).convert("RGB")
    arr = np.array(img)
    hist = []
    for ch in range(3):
        h, _ = np.histogram(arr[:, :, ch], bins=bins, range=(0, 256))
        hist.extend(h)
    return np.array(hist, dtype=float)

print("Extracting train features...")
X_train = normalize(np.array([extract_histogram(p) for p in train_images]))

print("Extracting test features...")
X_test  = normalize(np.array([extract_histogram(p) for p in test_images]))

# ── 3. Fit KMeans on train ───────────────────────────────────────────────────
N_CLUSTERS = 8
kmeans = KMeans(n_clusters=N_CLUSTERS, random_state=42, n_init=10)
train_labels = kmeans.fit_predict(X_train)

print("\nTrain cluster distribution:")
for k in range(N_CLUSTERS):
    print(f"  Cluster {k}: {np.sum(train_labels == k)} images")

# ── 4. Predict on test ───────────────────────────────────────────────────────
test_labels = kmeans.predict(X_test)

print("\nTest cluster distribution:")
for k in range(N_CLUSTERS):
    print(f"  Cluster {k}: {np.sum(test_labels == k)} images")

# ── 5. Visualise 5 train samples + 2 test samples per cluster ───────────────
COLS = 7  # 5 train + 2 test
fig, axes = plt.subplots(N_CLUSTERS, COLS, figsize=(COLS * 3, N_CLUSTERS * 2.5))

for k in range(N_CLUSTERS):
    tr_paths = [p for p, l in zip(train_images, train_labels) if l == k][:5]
    te_paths = [p for p, l in zip(test_images,  test_labels)  if l == k][:2]
    row_paths = tr_paths + te_paths
    for j in range(COLS):
        ax = axes[k][j]
        if j < len(row_paths):
            ax.imshow(mpimg.imread(row_paths[j]))
            if j == 0:
                ax.set_title(f"Cluster {k}", fontsize=9)
            if j == 5:
                ax.set_title("TEST →", fontsize=8, color="orange")
        ax.axis("off")

plt.suptitle("KMeans Clusters  |  cols 1-5: train   cols 6-7: test", fontsize=11)
plt.tight_layout()
plt.savefig("kmeans_clusters.png", dpi=100)
plt.show()
print("Saved kmeans_clusters.png")
```

### Tips
- Increase `N_CLUSTERS` (try 10–20) for finer groupings (team kits, ground types, crowd shots)
- Swap colour histograms for CNN embeddings (`torchvision` ResNet) for semantic clustering
- Use `inertia_` and elbow method to pick the optimal K

---

## Requirements

```
pip install huggingface_hub pillow scikit-learn matplotlib numpy
```