goyaljai commited on
Commit
7b6e87d
·
verified ·
1 Parent(s): a3abd61

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +65 -32
README.md CHANGED
@@ -25,6 +25,15 @@ size_categories:
25
  | Dimensions | 800 × 600 px (all uniform) |
26
  | Size | ~141 MB |
27
 
 
 
 
 
 
 
 
 
 
28
  ### Source breakdown
29
  | Source | Count |
30
  |---|---|
@@ -42,20 +51,26 @@ size_categories:
42
  ```python
43
  from huggingface_hub import snapshot_download
44
  from pathlib import Path
45
- from PIL import Image
46
- import numpy as np
47
 
48
- # Download dataset
49
- dataset_dir = snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset")
50
- image_paths = sorted(Path(dataset_dir).rglob("*.jpg"))
51
- print(f"Loaded {len(image_paths)} images")
 
 
 
 
 
 
 
 
52
  ```
53
 
54
  ---
55
 
56
- ## Example: K-Means Clustering
57
 
58
- Cluster the IPL images into N groups based on colour histogram features.
59
 
60
  ```python
61
  from huggingface_hub import snapshot_download
@@ -68,44 +83,62 @@ import matplotlib.pyplot as plt
68
  import matplotlib.image as mpimg
69
 
70
  # ── 1. Download dataset ──────────────────────────────────────────────────────
71
- dataset_dir = snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset")
72
- image_paths = sorted(Path(dataset_dir).rglob("*.jpg"))
73
- print(f"Found {len(image_paths)} images")
 
74
 
75
- # ── 2. Extract colour histogram features ────────────────────────────────────
76
  def extract_histogram(path, bins=32):
77
  img = Image.open(path).convert("RGB")
78
  arr = np.array(img)
79
  hist = []
80
- for channel in range(3): # R, G, B
81
- h, _ = np.histogram(arr[:, :, channel], bins=bins, range=(0, 256))
82
  hist.extend(h)
83
  return np.array(hist, dtype=float)
84
 
85
- features = np.array([extract_histogram(p) for p in image_paths])
86
- features = normalize(features) # L2 normalise
87
- print(f"Feature matrix: {features.shape}")
 
 
88
 
89
- # ── 3. K-Means clustering ───────────────────────────────────────────────────
90
  N_CLUSTERS = 8
91
  kmeans = KMeans(n_clusters=N_CLUSTERS, random_state=42, n_init=10)
92
- labels = kmeans.fit_predict(features)
93
 
 
94
  for k in range(N_CLUSTERS):
95
- count = np.sum(labels == k)
96
- print(f"Cluster {k}: {count} images")
97
 
98
- # ── 4. Visualise 5 samples per cluster ──────────────────────────────────────
99
- fig, axes = plt.subplots(N_CLUSTERS, 5, figsize=(15, N_CLUSTERS * 3))
 
 
100
  for k in range(N_CLUSTERS):
101
- cluster_paths = [p for p, l in zip(image_paths, labels) if l == k]
102
- samples = cluster_paths[:5]
103
- for j, path in enumerate(samples):
104
- axes[k][j].imshow(mpimg.imread(path))
105
- axes[k][j].axis("off")
106
- if j == 0:
107
- axes[k][j].set_title(f"Cluster {k}", fontsize=10)
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  plt.tight_layout()
110
  plt.savefig("kmeans_clusters.png", dpi=100)
111
  plt.show()
@@ -113,9 +146,9 @@ print("Saved kmeans_clusters.png")
113
  ```
114
 
115
  ### Tips
116
- - Increase `N_CLUSTERS` (try 10–20) for finer-grained groupings (team kits, ground types, crowd shots)
117
  - Swap colour histograms for CNN embeddings (`torchvision` ResNet) for semantic clustering
118
- - Use `KMeans(init='k-means++')` (default) for faster convergence
119
 
120
  ---
121
 
 
25
  | Dimensions | 800 × 600 px (all uniform) |
26
  | Size | ~141 MB |
27
 
28
+ ### Train / Test Split
29
+
30
+ | Split | Folder | Count | % |
31
+ |---|---|---|---|
32
+ | Train | `train/` | 674 | 70% |
33
+ | Test | `test/` | 289 | 30% |
34
+
35
+ > Split is random with `seed=42` for reproducibility.
36
+
37
  ### Source breakdown
38
  | Source | Count |
39
  |---|---|
 
51
  ```python
52
  from huggingface_hub import snapshot_download
53
  from pathlib import Path
 
 
54
 
55
+ # Download full dataset
56
+ dataset_dir = Path(snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset"))
57
+
58
+ # Train and test paths
59
+ train_dir = dataset_dir / "train"
60
+ test_dir = dataset_dir / "test"
61
+
62
+ train_images = sorted(train_dir.glob("*.jpg"))
63
+ test_images = sorted(test_dir.glob("*.jpg"))
64
+
65
+ print(f"Train: {len(train_images)} images")
66
+ print(f"Test : {len(test_images)} images")
67
  ```
68
 
69
  ---
70
 
71
+ ## Example: K-Means Clustering on Train Set, Evaluate on Test Set
72
 
73
+ Cluster IPL images by colour histogram features. Fit KMeans on the train split, then assign test images to the nearest cluster.
74
 
75
  ```python
76
  from huggingface_hub import snapshot_download
 
83
  import matplotlib.image as mpimg
84
 
85
  # ── 1. Download dataset ──────────────────────────────────────────────────────
86
+ dataset_dir = Path(snapshot_download(repo_id="goyaljai/IITB-PML-SEM1", repo_type="dataset"))
87
+ train_images = sorted((dataset_dir / "train").glob("*.jpg"))
88
+ test_images = sorted((dataset_dir / "test").glob("*.jpg"))
89
+ print(f"Train: {len(train_images)} | Test: {len(test_images)}")
90
 
91
+ # ── 2. Feature extraction (colour histogram) ─────────────────────────────────
92
  def extract_histogram(path, bins=32):
93
  img = Image.open(path).convert("RGB")
94
  arr = np.array(img)
95
  hist = []
96
+ for ch in range(3):
97
+ h, _ = np.histogram(arr[:, :, ch], bins=bins, range=(0, 256))
98
  hist.extend(h)
99
  return np.array(hist, dtype=float)
100
 
101
+ print("Extracting train features...")
102
+ X_train = normalize(np.array([extract_histogram(p) for p in train_images]))
103
+
104
+ print("Extracting test features...")
105
+ X_test = normalize(np.array([extract_histogram(p) for p in test_images]))
106
 
107
+ # ── 3. Fit KMeans on train ───────────────────────────────────────────────────
108
  N_CLUSTERS = 8
109
  kmeans = KMeans(n_clusters=N_CLUSTERS, random_state=42, n_init=10)
110
+ train_labels = kmeans.fit_predict(X_train)
111
 
112
+ print("\nTrain cluster distribution:")
113
  for k in range(N_CLUSTERS):
114
+ print(f" Cluster {k}: {np.sum(train_labels == k)} images")
 
115
 
116
+ # ── 4. Predict on test ───────────────────────────────────────────────────────
117
+ test_labels = kmeans.predict(X_test)
118
+
119
+ print("\nTest cluster distribution:")
120
  for k in range(N_CLUSTERS):
121
+ print(f" Cluster {k}: {np.sum(test_labels == k)} images")
122
+
123
+ # ── 5. Visualise 5 train samples + 2 test samples per cluster ───────��───────
124
+ COLS = 7 # 5 train + 2 test
125
+ fig, axes = plt.subplots(N_CLUSTERS, COLS, figsize=(COLS * 3, N_CLUSTERS * 2.5))
 
 
126
 
127
+ for k in range(N_CLUSTERS):
128
+ tr_paths = [p for p, l in zip(train_images, train_labels) if l == k][:5]
129
+ te_paths = [p for p, l in zip(test_images, test_labels) if l == k][:2]
130
+ row_paths = tr_paths + te_paths
131
+ for j in range(COLS):
132
+ ax = axes[k][j]
133
+ if j < len(row_paths):
134
+ ax.imshow(mpimg.imread(row_paths[j]))
135
+ if j == 0:
136
+ ax.set_title(f"Cluster {k}", fontsize=9)
137
+ if j == 5:
138
+ ax.set_title("TEST →", fontsize=8, color="orange")
139
+ ax.axis("off")
140
+
141
+ plt.suptitle("KMeans Clusters | cols 1-5: train cols 6-7: test", fontsize=11)
142
  plt.tight_layout()
143
  plt.savefig("kmeans_clusters.png", dpi=100)
144
  plt.show()
 
146
  ```
147
 
148
  ### Tips
149
+ - Increase `N_CLUSTERS` (try 10–20) for finer groupings (team kits, ground types, crowd shots)
150
  - Swap colour histograms for CNN embeddings (`torchvision` ResNet) for semantic clustering
151
+ - Use `inertia_` and elbow method to pick the optimal K
152
 
153
  ---
154