Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/sat2_soln.py
1901 views
1
"""This file contains code used in "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
import math
11
12
import thinkbayes2
13
import thinkplot
14
15
16
class Sat(thinkbayes2.Suite, thinkbayes2.Joint):
17
"""Represents the distribution of p_correct for a test-taker."""
18
19
def Likelihood(self, data, hypo):
20
"""Computes the likelihood of data under hypo.
21
22
data: boolean, whether the answer is correct
23
hypo: pair of (efficacy, difficulty)
24
"""
25
correct = data
26
e, d = hypo
27
p = ProbCorrect(e, d)
28
like = p if correct else 1-p
29
return like
30
31
32
def ProbCorrect(efficacy, difficulty, a=1):
33
"""Returns the probability that a person gets a question right.
34
35
efficacy: personal ability to answer questions
36
difficulty: how hard the question is
37
a: parameter that controls the shape of the curve
38
39
Returns: float prob
40
"""
41
return 1 / (1 + math.exp(-a * (efficacy - difficulty)))
42
43
44
def Update(p, q, correct):
45
"""Updates p and q according to correct.
46
47
p: prior distribution of efficacy for the test-taker
48
q: prior distribution of difficulty for the question
49
50
returns: pair of new Pmfs
51
"""
52
joint = thinkbayes2.MakeJoint(p, q)
53
suite = Sat(joint)
54
suite.Update(correct)
55
p, q = suite.Marginal(0, label=p.label), suite.Marginal(1, label=q.label)
56
return p, q
57
58
59
def main():
60
p1 = thinkbayes2.MakeNormalPmf(0, 1, 3, n=101)
61
p1.label = 'p1'
62
p2 = p1.Copy(label='p2')
63
64
q1 = thinkbayes2.MakeNormalPmf(0, 1, 3, n=101)
65
q1.label = 'q1'
66
q2 = q1.Copy(label='q2')
67
68
p1, q1 = Update(p1, q1, True)
69
p1, q2 = Update(p1, q2, True)
70
p2, q1 = Update(p2, q1, True)
71
p2, q2 = Update(p2, q2, False)
72
73
thinkplot.PrePlot(num=4, rows=2)
74
thinkplot.Pmfs([p1, p2])
75
thinkplot.Config(legend=True)
76
77
thinkplot.SubPlot(2)
78
thinkplot.Pmfs([q1, q2])
79
thinkplot.Show()
80
81
print('Prob p1 > p2', p1 > p2)
82
print('Prob q1 > q2', q1 > q2)
83
84
85
if __name__ == '__main__':
86
main()
87
88