-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathweighted_sample.py
More file actions
52 lines (43 loc) · 1.19 KB
/
weighted_sample.py
File metadata and controls
52 lines (43 loc) · 1.19 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
class WeightedSample:
"""
This class represents a weighted sample.
The weights of every instance in the sample
form a distribution.
"""
def __init__(self, instances):
"""
Initialize the sample with a list of
instances.
:param instances: list of instances.
"""
self.data = instances
self.sum = 0
for instance in self.data:
instance.weight = 1
self.sum += instance.weight
self.dist_sum = self.sum
def normalize(self):
"""
Make the weights conform to the
distribution
"""
z = self.dist_sum/self.sum
self.sum = 0
for instance in self.data:
instance.weight *= z
self.sum += instance.weight
def change_weight(self, i, new_weight):
"""
Change the weight of an instance in
the sample
:param i: index of the instance
:param new_weight: new weight
"""
self.sum -= self.data[i].weight
self.data[i].weight = new_weight
self.sum += new_weight
def size(self):
"""
:return: Sample size
"""
return len(self.data)