forked from AllenDowney/ProbablyOverthinkingIt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocial.py
More file actions
163 lines (121 loc) · 3.77 KB
/
social.py
File metadata and controls
163 lines (121 loc) · 3.77 KB
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
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import gzip
import math
import os
import sys
import Cdf
import Pmf
import myplot
import thinkstats
def BiasPmf(pmf, name, invert=False):
"""Returns the Pmf with oversampling proportional to value.
If pmf is the distribution of true values, the result is the
distribution that would be seen if values are oversampled in
proportion to their values; for example, if you ask students
how big their classes are, large classes are oversampled in
proportion to their size.
If invert=True, computes in inverse operation; for example,
unbiasing a sample collected from students.
Args:
pmf: Pmf object.
invert: boolean
Returns:
Pmf object
"""
new_pmf = pmf.Copy()
new_pmf.name = name
for x, p in pmf.Items():
if invert:
new_pmf.Mult(x, 1.0/x)
else:
new_pmf.Mult(x, x)
new_pmf.Normalize()
return new_pmf
def ReadFile(filename='soc-Slashdot0902.txt.gz', n=None):
"""Reads a compressed data file.
Args:
filename: string name of the file to read
"""
if filename.endswith('gz'):
fp = gzip.open(filename)
else:
fp = open(filename)
srcs = {}
for i, line in enumerate(fp):
if i == n:
break
if line.startswith('#'):
continue
src, dest = line.split()
srcs.setdefault(src, []).append(dest)
fp.close()
return srcs
def Summarize(srcs):
"""Computes the number of edges for each source."""
lens = [len(t) for t in srcs.itervalues()]
mu, sigma2 = thinkstats.MeanVar(lens)
print mu, math.sqrt(sigma2)
return lens
def MakePmfs(lens):
"""Computes the PMF of the given list and the biased PMF."""
pmf = Pmf.MakePmfFromList(lens, 'slashdot')
print 'unbiased mean', pmf.Mean()
biased_pmf = BiasPmf(pmf, 'biased')
print 'biased mean', biased_pmf.Mean()
return pmf, biased_pmf
def MakeFigures(pmf, biased_pmf):
"""Makes figures showing the CDF of the biased and unbiased PMFs"""
cdf = Cdf.MakeCdfFromPmf(pmf, 'unbiased')
print 'unbiased median', cdf.Percentile(50)
print 'percent < 100', cdf.Prob(100)
print 'percent < 1000', cdf.Prob(1000)
biased_cdf = Cdf.MakeCdfFromPmf(biased_pmf, 'biased')
print 'biased median', biased_cdf.Percentile(50)
myplot.Clf()
myplot.Cdfs([cdf, biased_cdf])
myplot.Save(root='slashdot.logx',
xlabel='Number of friends/foes',
ylabel='CDF',
xscale='log')
def MakeCdfs(lens):
cdf = Cdf.MakeCdfFromList(lens, 'slashdot')
myplot.Clf()
myplot.Cdf(cdf)
myplot.Save(root='slashdot.logx',
xlabel='Number of friends/foes',
ylabel='CDF',
xscale='log')
myplot.Clf()
myplot.Cdf(cdf, complement=True)
myplot.Save(root='slashdot.loglog',
xlabel='Number of friends/foes',
ylabel='CDF',
xscale='log',
yscale='log')
def PmfProbLess(pmf1, pmf2):
"""Probability that a value from pmf1 is less than a value from pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
float
"""
total = 0.0
for v1, p1 in pmf1.Items():
for v2, p2 in pmf2.Items():
if v1 < v2:
total += p1 * p2
return total
def main(name):
srcs = ReadFile(n=100000)
lens = Summarize(srcs)
pmf, biased_pmf = MakePmfs(lens)
MakeFigures(pmf, biased_pmf)
prob = PmfProbLess(pmf, biased_pmf)
print prob
if __name__ == '__main__':
main(*sys.argv)