Leacb4 commited on
Commit
4fba59e
·
verified ·
1 Parent(s): c09aeb7

Delete evaluation/sec5354_separation_semantic.py with huggingface_hub

Browse files
evaluation/sec5354_separation_semantic.py DELETED
@@ -1,329 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Sections 5.3.4 + 5.3.5 — Separation Score Analysis and Semantic Evaluation
4
- ===========================================================================
5
-
6
- Section 5.3.4: Separation score analysis on GAP-CLIP full embeddings vs baseline
7
- across three datasets (reported in paper body; detailed scores in main evaluation).
8
-
9
- Section 5.3.5: Zero-shot semantic evaluation comparing simple vs. extended text
10
- descriptions. Three evaluation modes on the internal dataset:
11
-
12
- (a) Color-only encoding (control): encodes only the color name — tests whether
13
- the embedding space is consistent for colors.
14
- (b) Text-to-text classification: encodes the full item description and finds
15
- the nearest color label in embedding space.
16
- (c) Image-to-text classification: encodes the item image and finds the nearest
17
- color label in embedding space.
18
-
19
- The 40%+ performance gap between GAP-CLIP and baseline on extended descriptions
20
- (Annex 9.7) demonstrates that the dedicated color/hierarchy subspaces act as
21
- semantic anchors under verbose, multi-attribute text inputs.
22
-
23
- Run directly:
24
- python sec5354_separation_semantic.py
25
-
26
- Paper reference: Sections 5.3.4 and 5.3.5.
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- import os
32
- import sys
33
- import warnings
34
- from pathlib import Path
35
-
36
- import matplotlib.pyplot as plt
37
- import numpy as np
38
- import pandas as pd
39
- import seaborn as sns
40
- import torch
41
- import torch.nn.functional as F
42
- from PIL import Image
43
- from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
44
- from torch.utils.data import Dataset
45
- from torchvision import transforms
46
- from tqdm import tqdm
47
-
48
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
49
- warnings.filterwarnings("ignore", category=FutureWarning)
50
- warnings.filterwarnings("ignore", category=UserWarning)
51
-
52
- # Ensure project root is importable when running this file directly.
53
- _PROJECT_ROOT = Path(__file__).resolve().parents[1]
54
- if str(_PROJECT_ROOT) not in sys.path:
55
- sys.path.insert(0, str(_PROJECT_ROOT))
56
-
57
- import config
58
- from evaluation.utils.model_loader import load_gap_clip, get_text_embedding, get_image_embedding
59
-
60
-
61
- # ---------------------------------------------------------------------------
62
- # Dataset
63
- # ---------------------------------------------------------------------------
64
-
65
- class CustomCSVDataset(Dataset):
66
- """Dataset backed by a local CSV; optionally loads images from disk.
67
-
68
- Each item returns (image_tensor, text, color).
69
- """
70
-
71
- def __init__(self, dataframe: pd.DataFrame, image_size: int = 224, load_images: bool = True):
72
- self.dataframe = dataframe
73
- self.image_size = image_size
74
- self.load_images = load_images
75
-
76
- self.transform = transforms.Compose([
77
- transforms.Resize((image_size, image_size)),
78
- transforms.ToTensor(),
79
- transforms.Normalize(
80
- mean=[0.48145466, 0.4578275, 0.40821073],
81
- std=[0.26862954, 0.26130258, 0.27577711],
82
- ),
83
- ])
84
-
85
- def __len__(self) -> int:
86
- return len(self.dataframe)
87
-
88
- def __getitem__(self, idx):
89
- row = self.dataframe.iloc[idx]
90
- text = row[config.text_column]
91
- color = row[config.color_column]
92
-
93
- if self.load_images and config.column_local_image_path in row:
94
- try:
95
- image = Image.open(row[config.column_local_image_path]).convert("RGB")
96
- image = self.transform(image)
97
- except Exception as e:
98
- print(f"Warning: could not load image {row.get(config.column_local_image_path, 'unknown')}: {e}")
99
- image = torch.zeros(3, self.image_size, self.image_size)
100
- else:
101
- image = torch.zeros(3, self.image_size, self.image_size)
102
-
103
- return image, text, color
104
-
105
-
106
- # ---------------------------------------------------------------------------
107
- # Evaluation functions (Section 5.3.5)
108
- # ---------------------------------------------------------------------------
109
-
110
- def evaluate_color_only_zero_shot(model, dataset, processor):
111
- """Control test: encode ONLY the color name (not the full text description).
112
-
113
- Tests whether the embedding space is consistent for color tokens regardless
114
- of surrounding context.
115
-
116
- Returns:
117
- (true_labels, predicted_labels, accuracy)
118
- """
119
- print("\n=== Section 5.3.5 (a): Color-Only Encoding — Control Test ===")
120
- print("Encodes ONLY the color name, not the full product description.")
121
-
122
- model.eval()
123
-
124
- all_colors = sorted({dataset[i][2] for i in range(len(dataset))})
125
- print(f"Colors found: {all_colors}")
126
-
127
- color_embeddings = {
128
- c: get_text_embedding(model, processor, config.device, c)
129
- for c in all_colors
130
- }
131
-
132
- true_labels, predicted_labels = [], []
133
- correct = 0
134
-
135
- for idx in tqdm(range(len(dataset)), desc="Evaluating (color-only)"):
136
- _, _, true_color = dataset[idx]
137
- true_color_emb = get_text_embedding(model, processor, config.device, true_color)
138
-
139
- best_sim = -1.0
140
- predicted_color = all_colors[0]
141
- for color, emb in color_embeddings.items():
142
- sim = F.cosine_similarity(true_color_emb.unsqueeze(0), emb.unsqueeze(0), dim=1).item()
143
- if sim > best_sim:
144
- best_sim, predicted_color = sim, color
145
-
146
- true_labels.append(true_color)
147
- predicted_labels.append(predicted_color)
148
- if true_color == predicted_color:
149
- correct += 1
150
-
151
- accuracy = accuracy_score(true_labels, predicted_labels)
152
- print(f"Color-only accuracy: {accuracy:.4f} ({accuracy * 100:.2f}%)")
153
- print(f"Correct: {correct}/{len(true_labels)}")
154
- return true_labels, predicted_labels, accuracy
155
-
156
-
157
- def evaluate_text_to_text_zero_shot(model, dataset, processor):
158
- """Text-to-text classification: compare full product description against color labels.
159
-
160
- Returns:
161
- (true_labels, predicted_labels, accuracy)
162
- """
163
- print("\n=== Section 5.3.5 (b): Text-to-Text Classification ===")
164
-
165
- model.eval()
166
-
167
- all_colors = sorted({dataset[i][2] for i in range(len(dataset))})
168
- print(f"Colors found: {all_colors}")
169
-
170
- color_embeddings = {
171
- c: get_text_embedding(model, processor, config.device, c)
172
- for c in all_colors
173
- }
174
-
175
- true_labels, predicted_labels = [], []
176
- correct = 0
177
-
178
- for idx in tqdm(range(len(dataset)), desc="Evaluating (text-to-text)"):
179
- _, text, true_color = dataset[idx]
180
- text_emb = get_text_embedding(model, processor, config.device, text)
181
-
182
- best_sim = -1.0
183
- predicted_color = all_colors[0]
184
- for color, emb in color_embeddings.items():
185
- sim = F.cosine_similarity(text_emb.unsqueeze(0), emb.unsqueeze(0), dim=1).item()
186
- if sim > best_sim:
187
- best_sim, predicted_color = sim, color
188
-
189
- true_labels.append(true_color)
190
- predicted_labels.append(predicted_color)
191
- if true_color == predicted_color:
192
- correct += 1
193
-
194
- accuracy = accuracy_score(true_labels, predicted_labels)
195
- print(f"Text-to-text accuracy: {accuracy:.4f} ({accuracy * 100:.2f}%)")
196
- print(f"Correct: {correct}/{len(true_labels)}")
197
- return true_labels, predicted_labels, accuracy
198
-
199
-
200
- def evaluate_image_to_text_zero_shot(model, dataset, processor):
201
- """Image-to-text classification: compare image embedding against color labels.
202
-
203
- Returns:
204
- (true_labels, predicted_labels, accuracy)
205
- """
206
- print("\n=== Section 5.3.5 (c): Image-to-Text Classification ===")
207
-
208
- model.eval()
209
-
210
- all_colors = sorted({dataset[i][2] for i in range(len(dataset))})
211
- print(f"Colors found: {all_colors}")
212
-
213
- color_embeddings = {
214
- c: get_text_embedding(model, processor, config.device, c)
215
- for c in all_colors
216
- }
217
-
218
- true_labels, predicted_labels = [], []
219
- correct = 0
220
-
221
- for idx in tqdm(range(len(dataset)), desc="Evaluating (image-to-text)"):
222
- image, _, true_color = dataset[idx]
223
- image_emb = get_image_embedding(model, image, config.device)
224
-
225
- best_sim = -1.0
226
- predicted_color = all_colors[0]
227
- for color, emb in color_embeddings.items():
228
- sim = F.cosine_similarity(image_emb, emb.unsqueeze(0), dim=1).item()
229
- if sim > best_sim:
230
- best_sim, predicted_color = sim, color
231
-
232
- true_labels.append(true_color)
233
- predicted_labels.append(predicted_color)
234
- if true_color == predicted_color:
235
- correct += 1
236
-
237
- accuracy = accuracy_score(true_labels, predicted_labels)
238
- print(f"Image-to-text accuracy: {accuracy:.4f} ({accuracy * 100:.2f}%)")
239
- print(f"Correct: {correct}/{len(true_labels)}")
240
- return true_labels, predicted_labels, accuracy
241
-
242
-
243
- # ---------------------------------------------------------------------------
244
- # Plotting
245
- # ---------------------------------------------------------------------------
246
-
247
- def plot_confusion_matrix(
248
- true_labels,
249
- predicted_labels,
250
- save_path=None,
251
- title_suffix: str = "text",
252
- ):
253
- """Generate and optionally save a percentage-based confusion matrix."""
254
- print("\n=== Generating Confusion Matrix ===")
255
-
256
- cm = confusion_matrix(true_labels, predicted_labels)
257
- unique_labels = sorted(set(true_labels + predicted_labels))
258
- accuracy = accuracy_score(true_labels, predicted_labels)
259
-
260
- cm_percent = np.round(cm.astype("float") / cm.sum(axis=1)[:, np.newaxis] * 100).astype(int)
261
-
262
- plt.figure(figsize=(12, 10))
263
- sns.heatmap(
264
- cm_percent,
265
- annot=True,
266
- fmt="d",
267
- cmap="Blues",
268
- cbar_kws={"label": "Percentage (%)"},
269
- xticklabels=unique_labels,
270
- yticklabels=unique_labels,
271
- )
272
- plt.title(
273
- f"Confusion Matrix — {title_suffix} | accuracy: {accuracy:.4f} ({accuracy * 100:.2f}%)",
274
- fontsize=16,
275
- )
276
- plt.xlabel("Predictions", fontsize=12)
277
- plt.ylabel("True colors", fontsize=12)
278
- plt.xticks(rotation=45, ha="right")
279
- plt.yticks(rotation=0)
280
- plt.tight_layout()
281
-
282
- if save_path:
283
- plt.savefig(save_path, dpi=300, bbox_inches="tight")
284
- print(f"Saved: {save_path}")
285
-
286
- plt.show()
287
- return cm
288
-
289
-
290
- # ---------------------------------------------------------------------------
291
- # Entry point
292
- # ---------------------------------------------------------------------------
293
-
294
- if __name__ == "__main__":
295
- print("=== GAP-CLIP: Sections 5.3.4 + 5.3.5 — Semantic Evaluation ===")
296
-
297
- model, processor = load_gap_clip(config.main_model_path, config.device)
298
-
299
- df = pd.read_csv(config.local_dataset_path)
300
-
301
- print("\n" + "=" * 80)
302
- print("(a) COLOR-TO-COLOR CLASSIFICATION — Control Test")
303
- print("=" * 80)
304
- dataset_color = CustomCSVDataset(df, load_images=False)
305
- true_c, pred_c, acc_c = evaluate_color_only_zero_shot(model, dataset_color, processor)
306
- plot_confusion_matrix(true_c, pred_c, save_path="confusion_matrix_color_only.png", title_suffix="color-only")
307
-
308
- print("\n" + "=" * 80)
309
- print("(b) TEXT-TO-TEXT CLASSIFICATION")
310
- print("=" * 80)
311
- dataset_text = CustomCSVDataset(df, load_images=False)
312
- true_t, pred_t, acc_t = evaluate_text_to_text_zero_shot(model, dataset_text, processor)
313
- plot_confusion_matrix(true_t, pred_t, save_path="confusion_matrix_text.png", title_suffix="text")
314
-
315
- print("\n" + "=" * 80)
316
- print("(c) IMAGE-TO-TEXT CLASSIFICATION")
317
- print("=" * 80)
318
- dataset_image = CustomCSVDataset(df, load_images=True)
319
- true_i, pred_i, acc_i = evaluate_image_to_text_zero_shot(model, dataset_image, processor)
320
- plot_confusion_matrix(true_i, pred_i, save_path="confusion_matrix_image.png", title_suffix="image")
321
-
322
- print("\n" + "=" * 80)
323
- print("SUMMARY — Section 5.3.5")
324
- print("=" * 80)
325
- print(f"(a) Color-only (control): {acc_c:.4f} ({acc_c * 100:.2f}%)")
326
- print(f"(b) Text-to-text: {acc_t:.4f} ({acc_t * 100:.2f}%)")
327
- print(f"(c) Image-to-text: {acc_i:.4f} ({acc_i * 100:.2f}%)")
328
- print(f"\nLoss from color-only vs text: {abs(acc_c - acc_t):.4f}")
329
- print(f"Difference text vs image: {abs(acc_t - acc_i):.4f}")