Spaces:
Sleeping
Sleeping
File size: 6,201 Bytes
a738d20 | 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 | import numpy as np
import pandas as pd
from scipy import stats
from config import PROFILE_TARGETS, PROFILES
class PsychometricComparator:
"""Compares human Rasch results to artificial crowd Rasch results and returns JSON-serializable data."""
def __init__(self, human_rasch, artificial_rasch, mcq_df):
self.human_rasch = human_rasch
self.art_rasch = artificial_rasch
self.mcq_df = mcq_df
n_items = min(len(human_rasch.b), len(artificial_rasch.b))
self.b_human = human_rasch.b[:n_items]
self.b_art = artificial_rasch.b[:n_items]
def pearson_r(self) -> float:
r, _ = stats.pearsonr(self.b_human, self.b_art)
return float(r)
def spearman_r(self) -> float:
r, _ = stats.spearmanr(self.b_human, self.b_art)
return float(r)
def mae(self) -> float:
return float(np.mean(np.abs(self.b_human - self.b_art)))
def rmse(self) -> float:
return float(np.sqrt(np.mean((self.b_human - self.b_art) ** 2)))
def compare_df(self) -> pd.DataFrame:
n = len(self.b_human)
delta = self.b_art - self.b_human
abs_delta = np.abs(delta)
agreement = []
for d in abs_delta:
if d < 0.50:
agreement.append("strong")
elif d < 1.00:
agreement.append("moderate")
else:
agreement.append("weak")
return pd.DataFrame({
"item_id": range(n),
"b_human": self.b_human,
"b_artificial": self.b_art,
"delta": delta,
"abs_delta": abs_delta,
"agreement": agreement,
})
def interpretation(self) -> str:
r = self.pearson_r()
if r >= 0.90: return "Excellent"
if r >= 0.75: return "Bon"
if r >= 0.60: return "Passable"
return "Insuffisant"
def full_metrics(self) -> dict:
return {
"pearson_r": self.pearson_r(),
"spearman_r": self.spearman_r(),
"mae": self.mae(),
"rmse": self.rmse(),
"interpretation": self.interpretation(),
}
def get_scatter_data(self) -> list:
"""Returns data for a scatter plot of b_human vs b_artificial."""
comp = self.compare_df()
return comp.to_dict(orient="records")
def get_distribution_data(self) -> dict:
"""Returns histograms for difficulty distributions."""
h_hist, h_bins = np.histogram(self.b_human, bins=30, density=True)
a_hist, a_bins = np.histogram(self.b_art, bins=30, density=True)
return {
"human": {
"counts": h_hist.tolist(),
"bins": h_bins.tolist()
},
"artificial": {
"counts": a_hist.tolist(),
"bins": a_bins.tolist()
}
}
def get_wright_map_data(self) -> dict:
"""Returns data to construct a Wright map on the frontend."""
# Histograms for theta (abilities) and b (difficulties)
t_h_hist, t_h_bins = np.histogram(self.human_rasch.theta, bins=25)
t_a_hist, t_a_bins = np.histogram(self.art_rasch.theta, bins=25)
b_h_hist, b_h_bins = np.histogram(self.b_human, bins=25)
b_a_hist, b_a_bins = np.histogram(self.b_art, bins=25)
return {
"abilities": {
"human": {"counts": t_h_hist.tolist(), "bins": t_h_bins.tolist()},
"artificial": {"counts": t_a_hist.tolist(), "bins": t_a_bins.tolist()}
},
"difficulties": {
"human": {"counts": b_h_hist.tolist(), "bins": b_h_bins.tolist()},
"artificial": {"counts": b_a_hist.tolist(), "bins": b_a_bins.tolist()}
}
}
def get_profile_perf_data(self, crowd_df: pd.DataFrame) -> dict:
"""Returns accuracy data grouped by profile and difficulty."""
perf = (
crowd_df
.groupby(["difficulty", "profile"])["is_correct"]
.mean()
.reset_index()
.rename(columns={"is_correct": "accuracy"})
)
difficulties = ["easy", "medium", "hard"]
profiles_list = list(PROFILES.keys())
data = []
for diff in difficulties:
row = {"difficulty": diff}
for profile in profiles_list:
mask = (perf["difficulty"] == diff) & (perf["profile"] == profile)
subset = perf[mask]
val = subset["accuracy"].values[0] if len(subset) > 0 else 0
row[profile] = float(val)
row[f"{profile}_target"] = float(PROFILE_TARGETS.get(profile, [0,0,0])[difficulties.index(diff)])
data.append(row)
return data
def plot_scatter(self, save_path):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(self.b_human, self.b_art, alpha=0.6)
ax.set_xlabel('Human Difficulty')
ax.set_ylabel('Artificial Difficulty')
ax.set_title('Scatter Comparison')
fig.savefig(save_path)
plt.close(fig)
def plot_difficulty_distributions(self, save_path):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.hist(self.b_human, bins=20, alpha=0.5, label='Human')
ax.hist(self.b_art, bins=20, alpha=0.5, label='Artificial')
ax.legend()
ax.set_title('Difficulty Distributions')
fig.savefig(save_path)
plt.close(fig)
def plot_wright_map(self, save_path):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
ax1.hist(self.human_rasch.theta, bins=20, orientation='horizontal')
ax1.set_title('Person Abilities')
ax2.hist(self.b_human, bins=20, orientation='horizontal', color='orange')
ax2.set_title('Item Difficulties')
fig.savefig(save_path)
plt.close(fig)
|