Skip to content

Commit 5e39c8f

Browse files
committed
Filled in WeightedMajority.
1 parent 274b629 commit 5e39c8f

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

learning.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from utils import *
44
import heapq, math, random
5+
from collections import defaultdict
56

67
#______________________________________________________________________________
78

@@ -401,7 +402,7 @@ def train(dataset):
401402
w = [1./N] * N
402403
h, z = [], []
403404
for k in range(K):
404-
h_k = L(dataset.examples, w)
405+
h_k = L(examples, w)
405406
h.append(h_k)
406407
error = sum(weight for example, weight in zip(examples, w)
407408
if example[target] != h_k(example))
@@ -416,8 +417,21 @@ def train(dataset):
416417
return WeightedMajority(h, z)
417418
return train
418419

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)
421435

422436
#_____________________________________________________________________________
423437
# Functions for testing learners on examples

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy