2
2
3
3
from utils import *
4
4
import heapq , math , random
5
+ from collections import defaultdict
5
6
6
7
#______________________________________________________________________________
7
8
@@ -401,7 +402,7 @@ def train(dataset):
401
402
w = [1. / N ] * N
402
403
h , z = [], []
403
404
for k in range (K ):
404
- h_k = L (dataset . examples , w )
405
+ h_k = L (examples , w )
405
406
h .append (h_k )
406
407
error = sum (weight for example , weight in zip (examples , w )
407
408
if example [target ] != h_k (example ))
@@ -416,8 +417,21 @@ def train(dataset):
416
417
return WeightedMajority (h , z )
417
418
return train
418
419
419
- def WeightedMajority (h , z ):
420
- unimplemented ()
420
+ def WeightedMajority (predictors , weights ):
421
+ "Return a predictor that takes a weighted vote."
422
+ def predict (example ):
423
+ return weighted_mode ((predictor (example ) for predictor in predictors ),
424
+ weights )
425
+ return predict
426
+
427
+ def weighted_mode (values , weights ):
428
+ """Return the value with the greatest total weight.
429
+ >>> weighted_mode('abbaa', [1,2,3,1,2])
430
+ 'b'"""
431
+ totals = defaultdict (int )
432
+ for v , w in zip (values , weights ):
433
+ totals [v ] += w
434
+ return max (values , key = totals .get )
421
435
422
436
#_____________________________________________________________________________
423
437
# Functions for testing learners on examples
0 commit comments