File size: 20,521 Bytes
3fe947e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# ════════════════════════════════════════════════════════════════════════════
#  SAE Bias Evaluation β€” Post-hoc Analysis & Plots  (matplotlib only)
#  Confirmed column schemas:
#    df_hc / df_neg:
#      index, feature, act_mean, ctrl_mean, ADS, selectivity_ratio,
#      group_label, final_concept, activation_label, social_attribute,
#      demographic_group, bias_direction, visual_stereotype, inferred_axis
#    df_sel:  feature, ADS, axis, selectivity_ratio, group_label, final_concept
#    df_all:  source, split, code, mean_activation, inferred_axis, bias_direction
#    df_sum:  final_concept, bias_direction, count, mean_act, demographic_group
#    df_cf:   feature, split, A, B, [C]
# ════════════════════════════════════════════════════════════════════════════

import os, json, warnings
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.cm as cm
import seaborn as sns
import squarify   # pip install squarify

warnings.filterwarnings("ignore")

RESULTS_DIR = "./results"
PLOT_DIR    = f"{RESULTS_DIR}/analysis_plots"
os.makedirs(PLOT_DIR, exist_ok=True)

plt.rcParams.update({
    "figure.dpi": 150,
    "savefig.bbox": "tight",
    "savefig.pad_inches": 0.25,
    "font.size": 11,
    "axes.titlesize": 13,
    "axes.titleweight": "bold",
    "axes.spines.top": False,
    "axes.spines.right": False,
})
PALETTE = sns.color_palette("tab10")

# ── Load ──────────────────────────────────────────────────────────────────
df_all = pd.read_csv(f"{RESULTS_DIR}/all_features.csv")
df_sel = pd.read_csv(f"{RESULTS_DIR}/selectivity_live.csv")
df_hc  = pd.read_csv(f"{RESULTS_DIR}/high_confidence_features.csv")
df_neg = pd.read_csv(f"{RESULTS_DIR}/negative_bias_features.csv")
df_sum = pd.read_csv(f"{RESULTS_DIR}/concept_summary.csv")
df_cf  = pd.read_csv(f"{RESULTS_DIR}/counterfactual_delta.csv")

# Normalise string columns
for df in [df_all, df_sel, df_hc, df_neg, df_sum, df_cf]:
    df.columns = df.columns.str.strip()

for col in ["bias_direction", "inferred_axis", "demographic_group", "axis"]:
    for df in [df_all, df_sel, df_hc, df_neg]:
        if col in df.columns:
            df[col] = df[col].str.strip().str.lower()

print(f"all={len(df_all)}  sel={len(df_sel)}  hc={len(df_hc)}"
      f"  neg={len(df_neg)}  cf={len(df_cf)}")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 1 β€” Bias Direction per Axis  (stacked bar)
#   source: df_hc  cols: inferred_axis, bias_direction
# ════════════════════════════════════════════════════════════════════════════
df_dir = (df_hc[df_hc["inferred_axis"] != "none"]
          .groupby(["inferred_axis", "bias_direction"])
          .size().reset_index(name="count"))
df_dir["pct"] = df_dir.groupby("inferred_axis")["count"] \
                       .transform(lambda x: x / x.sum() * 100)

pivot_dir = (df_dir.pivot_table(index="inferred_axis", columns="bias_direction",
                                 values="pct", aggfunc="sum")
             .reindex(columns=["positive", "neutral", "negative"], fill_value=0))

fig, ax = plt.subplots(figsize=(9, 5))
bar_colors = {"positive": "#2ecc71", "neutral": "#95a5a6", "negative": "#e74c3c"}
bottom = np.zeros(len(pivot_dir))
for direction in ["positive", "neutral", "negative"]:
    vals = pivot_dir.get(direction, pd.Series(0, index=pivot_dir.index)).values
    bars = ax.bar(pivot_dir.index, vals, bottom=bottom,
                  label=direction, color=bar_colors[direction])
    for bar, v in zip(bars, vals):
        if v > 5:
            ax.text(bar.get_x() + bar.get_width() / 2,
                    bar.get_y() + bar.get_height() / 2,
                    f"{v:.1f}%", ha="center", va="center",
                    fontsize=9, color="white", fontweight="bold")
    bottom += vals

ax.set_xlabel("Bias Axis"); ax.set_ylabel("% of Features")
ax.set_title("Bias Direction Distribution per Axis\n"
             "% of high-confidence features labelled by VLM")
ax.legend(loc="upper right", frameon=False)
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/01_bias_direction_by_axis.png")
plt.close(); print("Plot 1 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 2 β€” ADS Distribution per Axis  (box)
#   source: df_sel  cols: axis, ADS
# ════════════════════════════════════════════════════════════════════════════
df_ads = df_sel[df_sel["axis"] != "counterfactual"].copy()
axes_sorted = (df_ads.groupby("axis")["ADS"].median()
               .sort_values(ascending=False).index.tolist())
data_boxes = [df_ads[df_ads["axis"] == a]["ADS"].dropna().values
              for a in axes_sorted]

fig, ax = plt.subplots(figsize=(10, 5))
bp = ax.boxplot(data_boxes, patch_artist=True,
                flierprops=dict(marker="o", markersize=3, alpha=0.4),
                medianprops=dict(color="black", linewidth=2))
for patch, color in zip(bp["boxes"], PALETTE):
    patch.set_facecolor(color); patch.set_alpha(0.75)
ax.set_xticks(range(1, len(axes_sorted) + 1))
ax.set_xticklabels(axes_sorted, rotation=20, ha="right")
ax.set_xlabel("Bias Axis"); ax.set_ylabel("ADS")
ax.set_title("ADS Distribution per Bias Axis\n"
             "Activation Discriminativity Score (activator vs control)")
ax.axhline(0.05, color="grey", linestyle="--", linewidth=1, label="threshold 0.05")
ax.legend(frameon=False)
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/02_ADS_distribution_per_axis.png")
plt.close(); print("Plot 2 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 3 β€” Top-20 High-Confidence Features by ADS  (horizontal bar)
#   source: df_hc  cols: ADS, final_concept, group_label, inferred_axis
# ════════════════════════════════════════════════════════════════════════════
top20 = df_hc.nlargest(20, "ADS").copy()
top20["label"] = (top20["final_concept"].str[:36]
                  + "  [" + top20["group_label"].str[:14] + "]")
axis_color_map = {
    "gender": "#3498db", "caste_class": "#e74c3c",
    "religion": "#9b59b6", "region": "#f39c12",
    "skin_tone": "#1abc9c", "occupation": "#e67e22",
    "counterfactual": "#95a5a6"
}
bar_c = [axis_color_map.get(a, "#7f8c8d") for a in top20["inferred_axis"]]

fig, ax = plt.subplots(figsize=(12, 9))
y_pos = list(range(len(top20)))
ax.barh(y_pos, top20["ADS"].values, color=bar_c, alpha=0.85)
ax.set_yticks(y_pos)
ax.set_yticklabels(top20["label"].values, fontsize=9)
ax.invert_yaxis()
ax.set_xlabel("ADS Score"); ax.set_ylabel("Feature Concept")
ax.set_title("Top-20 High-Confidence Bias Features by ADS\n"
             "ADS β‰₯ 0.05 & selectivity_ratio β‰₯ 1.3")
for v, pos in zip(top20["ADS"].values, y_pos):
    ax.text(v + 0.001, pos, f"{v:.3f}", va="center", fontsize=8)
legend_patches = [mpatches.Patch(color=c, label=a)
                  for a, c in axis_color_map.items()
                  if a in top20["inferred_axis"].values]
ax.legend(handles=legend_patches, loc="lower right", frameon=False, fontsize=9)
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/03_top20_hc_features.png")
plt.close(); print("Plot 3 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 4 β€” Negative Stereotype Rate per Axis  (bar)
#   source: df_hc, df_neg  col: inferred_axis
# ════════════════════════════════════════════════════════════════════════════
total_per_axis = (df_hc[df_hc["inferred_axis"] != "none"]
                  .groupby("inferred_axis").size())
neg_per_axis   = df_neg.groupby("inferred_axis").size()
neg_rate = (neg_per_axis / total_per_axis * 100).dropna().reset_index()
neg_rate.columns = ["axis", "neg_rate"]
neg_rate = neg_rate.sort_values("neg_rate", ascending=False)

norm = plt.Normalize(neg_rate["neg_rate"].min(), neg_rate["neg_rate"].max())
bar_c4 = [cm.Reds(norm(v)) for v in neg_rate["neg_rate"]]

fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.bar(neg_rate["axis"], neg_rate["neg_rate"], color=bar_c4)
for bar, v in zip(bars, neg_rate["neg_rate"]):
    ax.text(bar.get_x() + bar.get_width() / 2,
            bar.get_height() + 0.4, f"{v:.1f}%",
            ha="center", va="bottom", fontsize=10)
ax.set_xlabel("Bias Axis"); ax.set_ylabel("Negative Rate (%)")
ax.set_title("Negative Stereotype Rate per Bias Axis\n"
             "% of features labelled 'negative' by VLM")
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/04_negative_rate_per_axis.png")
plt.close(); print("Plot 4 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 5 β€” Counterfactual ADS Heatmap
#   source: df_sel  cols: axis=="counterfactual", feature, ADS, group_label
# ════════════════════════════════════════════════════════════════════════════
df_cf_ads = df_sel[df_sel["axis"] == "counterfactual"].copy()
if not df_cf_ads.empty:
    top_feats = (df_cf_ads.groupby("feature")["ADS"].max()
                 .nlargest(15).index.tolist())
    pivot = (df_cf_ads[df_cf_ads["feature"].isin(top_feats)]
             .pivot_table(index="group_label", columns="feature",
                          values="ADS", aggfunc="mean").fillna(0))
    pivot.columns = [f"F{c}" for c in pivot.columns]

    fig, ax = plt.subplots(figsize=(12, max(4, len(pivot) * 0.55)))
    sns.heatmap(pivot, ax=ax, cmap="RdBu_r", center=0,
                vmin=-0.2, vmax=0.2, annot=True, fmt=".2f",
                linewidths=0.4, cbar_kws={"label": "ADS"})
    ax.set_xlabel("Feature Index"); ax.set_ylabel("Counterfactual Pair")
    ax.set_title("Counterfactual ADS Heatmap\n"
                 "Red = group A fires more  |  Blue = group B fires more")
    plt.tight_layout()
    plt.savefig(f"{PLOT_DIR}/05_counterfactual_heatmap.png")
    plt.close(); print("Plot 5 saved")
else:
    print("Plot 5 skipped β€” no counterfactual rows in df_sel")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 6 β€” Mean Activation per Group per Block  (grouped bar)
#   source: df_all  cols: source, split, code, mean_activation
# ════════════════════════════════════════════════════════════════════════════
code_col = "code" if "code" in df_all.columns else "split"
df_act = (df_all[df_all["source"] == "activator"]
          .groupby(["split", code_col])["mean_activation"]
          .mean().reset_index())
df_act["split_short"] = (df_act["split"]
                         .str.replace("_activator", "", regex=False)
                         .str.replace("_", " "))

codes  = df_act[code_col].unique()
groups = df_act["split_short"].unique()
x = np.arange(len(groups))
width = 0.8 / max(len(codes), 1)

fig, ax = plt.subplots(figsize=(13, 5))
for i, code in enumerate(codes):
    sub = df_act[df_act[code_col] == code].set_index("split_short")
    vals = [float(sub.loc[g, "mean_activation"])
            if g in sub.index else 0.0 for g in groups]
    offset = (i - len(codes) / 2 + 0.5) * width
    ax.bar(x + offset, vals, width=width * 0.9, label=str(code), alpha=0.85)

ax.set_xticks(x)
ax.set_xticklabels(groups, rotation=35, ha="right", fontsize=9)
ax.set_xlabel("Social Group"); ax.set_ylabel("Mean Activation")
ax.set_title("Mean SAE Activation per Group per Block\n"
             "Activator prompts β€” down.2.1 vs up.0.1")
ax.legend(frameon=False, title="Block")
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/06_mean_activation_per_group.png")
plt.close(); print("Plot 6 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 7 β€” High-Confidence Feature Count per Demographic Group (per-axis bars)
#   source: df_hc  cols: inferred_axis, group_label
# ════════════════════════════════════════════════════════════════════════════
df_demo = (df_hc.groupby(["inferred_axis", "group_label"])
           .size().reset_index(name="count")
           .sort_values(["inferred_axis", "count"], ascending=[True, False]))
axes_uniq = df_demo["inferred_axis"].unique()

fig, axes_arr = plt.subplots(1, len(axes_uniq),
                              figsize=(4.5 * len(axes_uniq), 5), sharey=False)
if len(axes_uniq) == 1:
    axes_arr = [axes_arr]

for i, (axis_name, grp) in enumerate(df_demo.groupby("inferred_axis")):
    ax = axes_arr[i]
    ax.barh(grp["group_label"], grp["count"],
            color=PALETTE[i % len(PALETTE)], alpha=0.82)
    ax.invert_yaxis()
    ax.set_title(axis_name, fontsize=10, fontweight="bold")
    ax.set_xlabel("Feature Count")
    ax.tick_params(axis="y", labelsize=8)

fig.suptitle("High-Confidence Features per Demographic Group",
             fontsize=13, fontweight="bold")
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/07_features_per_demo_group.png")
plt.close(); print("Plot 7 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 8 β€” ADS vs Selectivity Ratio Scatter
#   source: df_sel  cols: ADS, selectivity_ratio, axis, group_label
# ════════════════════════════════════════════════════════════════════════════
df_scat = df_sel[(df_sel["axis"] != "counterfactual")
                 & (df_sel["ADS"] > 0)].copy()
df_scat = df_scat.sample(min(2000, len(df_scat)), random_state=42)
axes_u = df_scat["axis"].unique()
cmap_s = {a: PALETTE[i % len(PALETTE)] for i, a in enumerate(axes_u)}

fig, ax = plt.subplots(figsize=(9, 6))
for axis_name, grp in df_scat.groupby("axis"):
    ax.scatter(grp["ADS"], grp["selectivity_ratio"],
               color=cmap_s[axis_name], alpha=0.4, s=20, label=axis_name)
ax.axhline(1.3, color="grey", linestyle="--", linewidth=1)
ax.axvline(0.05, color="grey", linestyle="--", linewidth=1)
ax.text(0.052, ax.get_ylim()[1] * 0.97, "ADS=0.05", fontsize=8, color="grey")
ax.text(df_scat["ADS"].min(), 1.32, "ratio=1.3", fontsize=8, color="grey")
ax.set_xlabel("ADS"); ax.set_ylabel("Selectivity Ratio")
ax.set_title("ADS vs Selectivity Ratio per Feature\n"
             "Top-right = most discriminative bias features")
ax.legend(frameon=False, markerscale=2, fontsize=9)
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/08_scatter_ADS_vs_selectivity.png")
plt.close(); print("Plot 8 saved")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 9 β€” Counterfactual Delta Aβˆ’B  (horizontal bar)
#   source: df_cf  cols: feature, split, A, B
# ════════════════════════════════════════════════════════════════════════════
if "A" in df_cf.columns and "B" in df_cf.columns:
    df_cf["delta_AB"] = pd.to_numeric(df_cf["A"], errors="coerce") \
                      - pd.to_numeric(df_cf["B"], errors="coerce")
    top_cf = df_cf.reindex(
        df_cf["delta_AB"].abs().nlargest(20).index).copy()
    top_cf["label"] = ("F" + top_cf["feature"].astype(str)
                       + "  |  " + top_cf["split"].str[:22])
    bar_c9 = ["#3498db" if v > 0 else "#e74c3c"
               for v in top_cf["delta_AB"]]

    fig, ax = plt.subplots(figsize=(11, 8))
    y_pos = list(range(len(top_cf)))
    ax.barh(y_pos, top_cf["delta_AB"].values, color=bar_c9, alpha=0.85)
    ax.set_yticks(y_pos)
    ax.set_yticklabels(top_cf["label"].values, fontsize=9)
    ax.invert_yaxis()
    ax.axvline(0, color="black", linewidth=1)
    ax.set_xlabel("Delta (Aβˆ’B)")
    ax.set_title("Counterfactual Delta (Aβˆ’B) per Feature\n"
                 "Blue = group A fires more  |  Red = group B fires more")
    ax.legend(handles=[
        mpatches.Patch(color="#3498db", label="Group A > Group B"),
        mpatches.Patch(color="#e74c3c", label="Group B > Group A")
    ], frameon=False)
    plt.tight_layout()
    plt.savefig(f"{PLOT_DIR}/09_counterfactual_delta_bar.png")
    plt.close(); print("Plot 9 saved")
else:
    print("Plot 9 skipped β€” A/B columns not found in counterfactual_delta.csv")


# ════════════════════════════════════════════════════════════════════════════
# PLOT 10 β€” Concept Treemap  (squarify)
#   source: df_sum  cols: final_concept, bias_direction, count, mean_act
# ════════════════════════════════════════════════════════════════════════════
df_tree = df_sum.copy()
df_tree["count"]    = pd.to_numeric(df_tree["count"], errors="coerce").fillna(1)
df_tree["mean_act"] = pd.to_numeric(df_tree["mean_act"], errors="coerce").fillna(0)
df_tree = df_tree.nlargest(40, "mean_act")
df_tree["label"] = df_tree["final_concept"].str[:28]

norm10   = plt.Normalize(df_tree["mean_act"].min(), df_tree["mean_act"].max())
t_colors = [cm.Oranges(norm10(v)) for v in df_tree["mean_act"]]

fig, ax = plt.subplots(figsize=(14, 8))
squarify.plot(sizes=df_tree["count"].values,
              label=df_tree["label"].values,
              color=t_colors, alpha=0.85, ax=ax,
              text_kwargs={"fontsize": 7})
ax.axis("off")
ax.set_title("Top Feature Concepts by Bias Direction\n"
             "Size = frequency  |  Color = mean activation (darker = higher)",
             fontsize=12, fontweight="bold")
sm = cm.ScalarMappable(cmap="Oranges", norm=norm10)
sm.set_array([])
plt.colorbar(sm, ax=ax, shrink=0.6, label="Mean Activation")
plt.tight_layout()
plt.savefig(f"{PLOT_DIR}/10_concept_treemap.png")
plt.close(); print("Plot 10 saved")

print(f"\nβœ“ All 10 plots saved β†’ {PLOT_DIR}")