File size: 6,709 Bytes
03a6c4c | 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 | #!/usr/bin/env python3
"""
example.py β Usage demonstrations for hv_chemical_classifier.
NumPy only.
"""
import numpy as np
from hv_chemical_classifier import (
Hypothesis, EvidenceChannel, ChemicalClassifier,
adaptive_tempering, true_voi, correlation_discount,
make_paleo_scenario,
)
def demo_basic():
print("=" * 72)
print("Demo 1 β basic classification")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Observe a strong sauropod-like signal
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
r = clf.classify()
print(f" Winner: {r['winner']}")
print(f" Posterior: " +
", ".join(f"{h.name}={p:.3f}"
for h, p in zip(clf.hypotheses, r['posterior'])))
print()
def demo_ambivalence():
print("=" * 72)
print("Demo 2 β honest refusal via multi-seed bistability")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Weak, ambiguous signal
clf.observe('femur_morphology', 1)
clf.observe('tooth_shape', 1)
r = clf.classify_multiseed(n_seeds=20, n_steps=500)
print(f" Verdict: {r['verdict']}")
print(f" Ambiguous: {r['ambiguous']}")
print(f" Winner counts: {r['winner_counts']}")
print()
def demo_tempering():
print("=" * 72)
print("Demo 3 β adaptive tempering")
print("=" * 72)
print()
# Sharp vs weak specimen
for label, obs in [
('sharp', {'femur_morphology': 2, 'tooth_shape': 0,
'bone_density': 2, 'cortical_thickness': 2}),
('weak', {'femur_morphology': 1, 'tooth_shape': 1}),
]:
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
for k, v in obs.items():
clf.observe(k, v)
log_lik = clf.raw_log_likelihoods()
alpha = adaptive_tempering(log_lik)
r = clf.classify(apply_tempering=True)
print(f" {label:<8s} Ξ± = {alpha:.3f} winner = {r['winner']}")
print()
def demo_discount():
print("=" * 72)
print("Demo 4 β correlation discount")
print("=" * 72)
print()
for label, group in [('independent', None), ('correlated', 'group')]:
hyp = [Hypothesis('A', prior=0.5), Hypothesis('B', prior=0.5)]
channels = [
EvidenceChannel(f'ch{i}',
np.array([[0.6, 0.4], [0.4, 0.6]]),
cost=1.0, correlation_group=group)
for i in range(5)
]
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in channels:
clf.add_channel(c)
for c in channels:
clf.observe(c.name, 1)
log_lik = clf.raw_log_likelihoods(
apply_discount=(label == 'correlated'))
raw_odds = float(log_lik[1] - log_lik[0])
print(f" {label:<12s} raw log-odds = {raw_odds:+.4f}")
print()
def demo_voi():
print("=" * 72)
print("Demo 5 β true VOI (which channel to run next?)")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Partial evidence
clf.observe('femur_morphology', 1)
a = clf.effective_rates()
clf.reset_concentrations()
traj, _ = clf.evolve(a, 300, 0.02)
p = traj[-1] / traj[-1].sum()
candidates = ['tooth_shape', 'bone_density',
'cortical_thickness', 'joint_geometry']
voi = true_voi(clf, p, candidates)
print(f" Current posterior: " +
", ".join(f"{h.name}={p[i]:.3f}"
for i, h in enumerate(clf.hypotheses)))
print()
print(f" {'channel':<22s} {'VOI/cost':>10s}")
print(" " + "-" * 36)
for name, r in sorted(voi.items(), key=lambda x: -x[1]['voi_per_cost']):
print(f" {name:<22s} {r['voi_per_cost']:>10.5f}")
print()
def demo_messenger():
print("=" * 72)
print("Demo 6 β pairwise messenger as confidence signal")
print("=" * 72)
print()
# Scenario: clear winner
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
a = clf.effective_rates()
clf.reset_concentrations()
traj, M = clf.evolve(a, 500, 0.02, track_messenger=True)
print(f" Scenario: clear winner")
print(f" Peak messenger: {M.max():.4f} at step {int(np.argmax(M))}")
print(f" Final messenger: {M[-1]:.6f}")
print()
# Peak occurs during the transition, then decays
peak_idx = int(np.argmax(M))
print(f" Messenger trajectory (every 50 steps):")
for t in range(0, 500, 50):
bar = "β" * int(M[t] * 40)
print(f" step {t:>3d} M = {M[t]:.4f} {bar}")
print()
def demo_stopping():
print("=" * 72)
print("Demo 7 β entropy stopping vs max-posterior stopping")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
clf.observe('cortical_thickness', 2)
a = clf.effective_rates()
clf.reset_concentrations()
traj, _ = clf.evolve(a, 500, 0.02)
threshold = 0.85
stop_step = None
for t in range(len(traj)):
H = traj[t]
p = H / H.sum()
if p.max() > threshold:
stop_step = t
break
print(f" Threshold: max posterior > {threshold}")
print(f" Stopping step: {stop_step}")
print()
print(f" {'step':>5s} {'max p':>8s} {'entropy':>10s} {'stop?':>6s}")
print(" " + "-" * 36)
for t in [0, 50, 100, 150, 200, 300, 499]:
H = traj[t]
p = H / H.sum()
p = np.maximum(p, 1e-12)
ent = -np.sum(p * np.log(p))
stopped = "β" if (stop_step is not None and t >= stop_step) else ""
print(f" {t:>5d} {p.max():>8.4f} {ent:>10.4f} {stopped:>6s}")
print()
def main():
demo_basic()
demo_ambivalence()
demo_tempering()
demo_discount()
demo_voi()
demo_messenger()
demo_stopping()
if __name__ == "__main__":
main() |