-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollaborativeStrategy.py
More file actions
93 lines (66 loc) · 2.79 KB
/
CollaborativeStrategy.py
File metadata and controls
93 lines (66 loc) · 2.79 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 21 19:44:34 2017
@author: charley
"""
from __future__ import division
import logging
import math
import copy
import os
import numpy as np
import matplotlib.pyplot as plt
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from libact.models import SVM
from libact.base.dataset import Dataset, import_libsvm_sparse
from libact.base.interfaces import QueryStrategy, Model
from libact.query_strategies import UncertaintySampling, RandomSampling, QUIRE, HintSVM
import libact.models
from libact.utils import inherit_docstring_from, seed_random_state, zip
from alearner import Alearner
LOGGER = logging.getLogger(__name__)
class CollaborativeStrategy(QueryStrategy):
def __init__(self, *args, **kwargs):
super(CollaborativeStrategy, self).__init__(*args, **kwargs)
self.baseModel = kwargs.pop('baseModel',None)
if self.baseModel is None:
raise ValueError("Collaborative Strategy requires a base model")
self.queryStrategies = kwargs.pop('queryStrategies', None)
if self.queryStrategies is None or not isinstance(self.queryStrategies, list):
raise ValueError("Collaborative Strategy requires a list of Query strategies ")
self.baseModel.train(self.dataset)
self.aLearners = list()
for qs in self.queryStrategies:
a1 = Alearner(qs, hisModel = SVM(kernel='linear', decision_function_shape='ovr'), hisDataset= copy.deepcopy(self.dataset))
self.aLearners.append(a1)
self.baseModel.train(self.dataset)
@inherit_docstring_from(QueryStrategy)
def update(self, entry_id, label):
self.dataset.update(entry_id, label)
self.send_feedback(entry_id, label)
@inherit_docstring_from(QueryStrategy)
def make_query(self):
votes = {}
for i in range(len(self.aLearners)):
aQueriedPoint, weigted_confidence = self.aLearners[i].vote()
if aQueriedPoint in votes:
votes[aQueriedPoint] += weigted_confidence
else:
votes[aQueriedPoint] = weigted_confidence
# check if all values are the same
aKey = next(iter(votes))
similarValues = all(value == votes[aKey] for value in votes.values())
if(similarValues):
a = np.array(list(votes.keys()))
ask_id = np.random.choice(a, 1)
ask_id = ask_id[0] # turn array to scalar
else:
ask_id =max(votes)
return ask_id
def send_feedback(self, ask_id, theLabel):
for l in self.aLearners:
l.receive_feedback(ask_id, theLabel)