-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmva.py
68 lines (49 loc) · 1.41 KB
/
mva.py
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
"""
Mean Value Adjuster
===================
A python class to adjust the mean (average) value of a dataset by weighing each
value based on its z-score. Values closer to the mean are considered "better"
and so are given more weight.
Usage
-----
Very useful for giving less weight to "troll votes" in rating systems.
Example
-------
>>> values = [100,70,88,91,85,60,99,2]
>>> adjuster = Adjuster(values)
>>> adjuster.get_true_mean()
74.375
>>> adjuster.get_adjusted_mean()
83.54110999572508
"""
from math import cos
from statistics import mean, stdev
class Adjuster:
def __init__(self, ls=[0]):
self.votes = ls
def _apply_weight(self):
mn = mean(self.votes)
sd = stdev(self.votes)
weights = []
for x in self.votes:
z_score = (x - mn) / sd if sd is not 0 else 0
weight = cos(z_score)
if weight < 0:
weight = 0
weights.append({'value': x, 'weight': weight})
return weights
def get_true_mean(self):
return mean(self.votes)
def get_adjusted_mean(self):
weights = self._apply_weight()
sum_value = 0
sum_weight = 0
for item in weights:
sum_value += item['value'] * item['weight']
sum_weight += item['weight']
return sum_value / sum_weight
def main():
import doctest
doctest.testmod()
if __name__ == '__main__':
main()