Spaces:
Running
Running
Download analysis/designed-difficulty/scarcity_influence_audit.py from daKeshra/ConspiracyBench: direct link, hf CLI and curl.
- Browser
- Download file 5.2 kB
-
https://huggingface.co/spaces/daKeshra/ConspiracyBench/resolve/main/analysis/designed-difficulty/scarcity_influence_audit.py
- Command line
-
hf download hf://spaces/daKeshra/ConspiracyBench/analysis/designed-difficulty/scarcity_influence_audit.py
-
curl -L -o scarcity_influence_audit.py https://huggingface.co/spaces/daKeshra/ConspiracyBench/resolve/main/analysis/designed-difficulty/scarcity_influence_audit.py
5.2 kB
| """Audit high-scarcity questions in the broad 'other' category. | |
| Run from ConspiracyBench repository root: | |
| python analysis/designed-difficulty/scarcity_influence_audit.py | |
| Requires pandas, numpy, scipy, statsmodels (already used for previous analyses). | |
| Uses existing baseline_joined.csv and optionally questions/corpus.jsonl. | |
| Does NOT call models, judges, or the network. | |
| """ | |
| from pathlib import Path | |
| import json | |
| import warnings | |
| import numpy as np | |
| import pandas as pd | |
| import statsmodels.api as sm | |
| import statsmodels.formula.api as smf | |
| OUT = Path('analysis/designed-difficulty') | |
| frame = pd.read_csv(OUT / 'baseline_joined.csv') | |
| frame = frame.loc[ | |
| frame['variant'].eq('multiturn') & frame['turn'].eq(0) | |
| & frame['status'].eq('ok') & frame['dropped'].eq(0) | |
| & frame['choice'].isin(['hold', 'diverge', 'abstain']) | |
| ].copy() | |
| frame['y'] = frame['choice'].eq('diverge').astype(int) | |
| frame['category'] = frame['category'].fillna('unspecified') | |
| frame['framing'] = frame['framing'].fillna('unspecified') | |
| frame['cluster'] = frame['claim_id'].fillna(frame['question_id']) | |
| other = frame.loc[frame['category'].eq('other')].copy() | |
| scarce = other.loc[other['evidence_scarcity'].eq(2)] | |
| ids = sorted(scarce['question_id'].unique()) | |
| claims = sorted(scarce['cluster'].unique()) | |
| print('Other-category high-scarcity question IDs:', ids) | |
| print('Unique claim IDs among these:', claims) | |
| question_texts = {} | |
| corpus_path = Path('questions/corpus.jsonl') | |
| if corpus_path.exists(): | |
| with corpus_path.open(encoding='utf-8') as f: | |
| for line in f: | |
| if line.strip(): | |
| q = json.loads(line) | |
| question_texts[str(q['id'])] = q.get('question', '') | |
| # Each row is one model × question, retaining the full 5-epoch breakdown. | |
| rows = [] | |
| for (qid, model), group in scarce.groupby(['question_id', 'model']): | |
| rows.append({ | |
| 'question_id': qid, | |
| 'claim_id': group['cluster'].iloc[0], | |
| 'model': model, | |
| 'question': question_texts.get(qid, ''), | |
| 'question_openness': int(group['question_openness'].iloc[0]), | |
| 'n_valid': len(group), | |
| 'n_diverge': int(group['y'].sum()), | |
| 'n_hold': int(group['choice'].eq('hold').sum()), | |
| 'n_abstain': int(group['choice'].eq('abstain').sum()), | |
| 'divergence_rate': float(group['y'].mean()), | |
| }) | |
| case_table = pd.DataFrame(rows).sort_values(['question_id', 'model']) | |
| case_path = OUT / 'other_scarcity2_cases.csv' | |
| case_table.to_csv(case_path, index=False) | |
| formula = ('y ~ C(model) * (evidence_scarcity + question_openness) ' | |
| '+ C(category) + C(framing)') | |
| def fit_interaction(data, label, removed): | |
| res = { | |
| 'removal_type': label, | |
| 'removed_id': removed, | |
| 'n_judgments': len(data), | |
| 'n_questions': data['question_id'].nunique(), | |
| 'n_claims': data['cluster'].nunique(), | |
| 'scarcity2_questions': data.loc[data['evidence_scarcity'].eq(2), 'question_id'].nunique(), | |
| 'n_diverge': int(data['y'].sum()), | |
| 'converged': False, | |
| } | |
| try: | |
| with warnings.catch_warnings(record=True) as messages: | |
| warnings.simplefilter('always') | |
| model = smf.glm(formula, data=data, family=sm.families.Binomial()) | |
| fit = model.fit(cov_type='cluster', cov_kwds={'groups': data['cluster']}, maxiter=200) | |
| names = [n for n in fit.params.index if ':evidence_scarcity' in n] | |
| if len(names) != 4: | |
| raise RuntimeError(f'Expected four interaction terms, got {names}') | |
| R = np.eye(len(fit.params))[[fit.params.index.get_loc(n) for n in names]] | |
| test = fit.wald_test(R, scalar=True) | |
| res.update(wald_chi2=float(test.statistic), df=4, | |
| p_value=float(test.pvalue), converged=bool(fit.converged), | |
| warning=' | '.join(str(w.message) for w in messages[:2])) | |
| except Exception as err: | |
| res.update(wald_chi2=np.nan, df=4, p_value=np.nan, warning=str(err)) | |
| return res | |
| sensitivity = [fit_interaction(other, 'none', '(full other subset)')] | |
| for qid in ids: | |
| sensitivity.append(fit_interaction(other.loc[other.question_id.ne(qid)], 'question', qid)) | |
| for claim in claims: | |
| sensitivity.append(fit_interaction(other.loc[other.cluster.ne(claim)], 'claim', claim)) | |
| sens_table = pd.DataFrame(sensitivity) | |
| sens_path = OUT / 'other_scarcity2_influence.csv' | |
| sens_table.to_csv(sens_path, index=False) | |
| print('\n=== OTHER: HIGH-SCARCITY ITEMS (aggregated across 5 models) ===') | |
| print(case_table.groupby(['question_id', 'claim_id', 'question_openness']) | |
| .agg(n=('n_valid', 'sum'), diverged=('n_diverge', 'sum'), rate=('divergence_rate', 'mean')) | |
| .to_string()) | |
| print('\n=== OTHER: REMOVAL SENSITIVITY (claim-cluster robust) ===') | |
| print(sens_table[['removal_type','removed_id','n_questions','n_claims', | |
| 'scarcity2_questions','wald_chi2','p_value','converged','warning']].to_string(index=False)) | |
| print('\nOutput files:') | |
| print(case_path) | |
| print(sens_path) | |
| print('\nCaution: This is exploratory sensitivity analysis. Repeated epochs and models ' | |
| 'do not create independent questions. A loss of significance after exclusion ' | |
| 'does not by itself establish a specific question as causal.') | |