source: orange/Orange/multilabel/brknn.py @ 9994:1073e0304a87

Revision 9994:1073e0304a87, 7.2 KB checked in by Matija Polajnar <matija.polajnar@…>, 2 years ago (diff)

Remove links from documentation to datasets. Remove datasets reference directory.

Line 
1"""
2.. index:: BR-kNN Learner
3
4***************************************
5BR-kNN Learner
6***************************************
7
8BR-kNN Classification is an adaptation of the kNN algorithm for multi-label classification that
9is conceptually equivalent to using the popular Binary Relevance problem transformation method
10in conjunction with the kNN algorithm. It also implements two extensions of BR-kNN.
11For more information, see E. Spyromitros, G. Tsoumakas, I. Vlahavas,
12`An Empirical Study of Lazy Multilabel Classification Algorithms <http://mlkd.csd.auth.gr/multilabel.html>`_,
13Proc. 5th Hellenic Conference on Artificial Intelligence (SETN 2008), Springer, Syros, Greece, 2008. 
14
15.. index:: BR-kNN Learner
16.. autoclass:: Orange.multilabel.BRkNNLearner
17   :members:
18   :show-inheritance:
19 
20   :param instances: a table of instances.
21   :type instances: :class:`Orange.data.Table`
22
23.. index:: BRkNN Classifier
24.. autoclass:: Orange.multilabel.BRkNNClassifier
25   :members:
26   :show-inheritance:
27   
28Examples
29========
30
31The following example demonstrates a straightforward invocation of
32this algorithm (:download:`mlc-classify.py <code/mlc-classify.py>`):
33
34.. literalinclude:: code/mlc-classify.py
35   :lines: 6-9
36
37"""
38import random
39import math
40
41import Orange
42import multiknn as _multiknn
43
44class BRkNNLearner(_multiknn.MultikNNLearner):
45    """
46    Class implementing the BR-kNN learner.
47   
48    .. attribute:: k
49   
50        Number of neighbours. If set to 0 (which is also the default value),
51        the square root of the number of instances is used.
52   
53    .. attribute:: ext
54   
55        Extension type. The default is None, means 'Standard BR'; 'a' means
56        predicting top ranked label in case of empty prediction set; 'b' means
57        predicting top n ranked labels based on size of labelset in neighbours.
58   
59    .. attribute:: knn
60       
61        :class:`Orange.classification.knn.FindNearest` for nearest neighbor search
62   
63    """
64    def __new__(cls, instances = None, k=1, ext = None, weight_id = 0, **argkw):
65        """
66        Constructor of BRkNNLearner
67       
68        :param instances: a table of instances.
69        :type instances: :class:`Orange.data.Table`
70       
71        :param k: number of nearest neighbours used in classification
72        :type k: int
73       
74        :param ext: extension type (default value is None which yields
75            the Standard BR), values 'a' and 'b' are also possible.
76        :type ext: string
77       
78        :rtype: :class:`BRkNNLearner`
79        """
80       
81        self = _multiknn.MultikNNLearner.__new__(cls, k, **argkw)
82       
83        if ext not in [None, 'a', 'b']:
84            raise ValueError, "Invalid ext value: should be None, 'a' or 'b'."
85        self.ext = ext
86       
87        if instances:
88            self.instances = instances
89            self.__init__(**argkw)
90            return self.__call__(instances,weight_id)
91        else:
92            return self
93
94    def __call__(self, instances, weight_id = 0, **kwds):
95        if not Orange.multilabel.is_multilabel(instances):
96            raise TypeError("The given data set is not a multi-label data set.")
97
98        for k in kwds.keys():
99            self.__dict__[k] = kwds[k]
100        self._build_knn(instances)
101
102        labeling_f = [BRkNNClassifier.get_labels, BRkNNClassifier.get_labels_a,
103                      BRkNNClassifier.get_labels_b][ [None, 'a', 'b'].index(self.ext) ]
104       
105        return BRkNNClassifier(instances = instances,
106                               ext = self.ext,
107                               knn = self.knn,
108                               k = self.k,
109                               labeling_f = labeling_f)
110
111class BRkNNClassifier(_multiknn.MultikNNClassifier):
112    def __call__(self, instance, result_type=Orange.classification.Classifier.GetValue):
113        """
114        :rtype: a list of :class:`Orange.data.Value`, a list of :class:`Orange.statistics.distribution.Distribution`, or a tuple with both
115        """
116        domain = self.instances.domain
117
118        neighbours = self.knn(instance, self.k)
119       
120        prob = self.get_prob(neighbours)
121       
122        labels = self.labeling_f(self, prob, neighbours)
123       
124        if result_type == Orange.classification.Classifier.GetValue:
125            return labels
126
127        dists = [Orange.statistics.distribution.Discrete([1-p, p]) for p in prob]
128        for v, d in zip(self.instances.domain.class_vars, dists):
129            d.variable = v
130
131        if result_type == Orange.classification.Classifier.GetProbabilities:
132            return dists
133        return labels, dists
134   
135    def get_prob(self, neighbours):
136        """
137        Calculates the probabilities of the labels, based on the neighboring
138        instances.
139     
140        :param neighbours: a list of nearest neighboring instances.
141        :type neighbours: list of :class:`Orange.data.Instance`
142       
143        :rtype: the prob of the labels
144       
145        """
146        total = 0
147        label_count = len(self.instances.domain.class_vars)
148        confidences = [1.0 / max(1, len(self.instances))] * label_count
149
150        total = float(label_count) / max(1, len(self.instances))
151       
152        for neigh in neighbours:
153            vals = neigh.get_classes()
154            for j, value in enumerate(vals):
155                if value == '1':
156                    confidences[j] += 1
157            total += 1
158
159        #Normalize distribution
160        if total > 0:
161            confidences = [con/total for con in confidences]
162       
163        return confidences
164   
165    def get_labels(self, prob, _neighs=None, thresh=0.5):
166        return [Orange.data.Value(lvar, str(int(p>thresh)))
167                for p, lvar in zip(prob, self.instances.domain.class_vars)]
168   
169    def get_labels_a(self, prob, _neighs=None):
170        """
171        used for BRknn-a
172       
173        :param prob: the probabilities of the labels
174        :type prob: list of double
175       
176        :rtype: the list label value
177        """
178        labels = self.get_labels(prob)
179           
180        #assign the class with the greatest confidence
181        if all(l.value=='0' for l in labels):
182            index = max((v,i) for i,v in enumerate(prob))[1]
183            labels[index].value = '1'
184       
185        return labels
186   
187    def get_labels_b(self, prob, neighs):
188        """
189        used for BRknn-b
190       
191        :param prob: the probabilities of the labels
192        :type prob: list of double
193       
194        :rtype: the list label value
195        """
196       
197        labels = [Orange.data.Value(lvar, '0')
198                  for p, lvar in zip(prob, self.instances.domain.class_vars)]
199       
200        avg_label_cnt = sum(sum(l.value=='1' for l in n.get_classes())
201                            for n in neighs) / float(len(neighs))
202        avg_label_cnt = int(round(avg_label_cnt))
203       
204        for p, lval in sorted(zip(prob, labels), reverse=True)[:avg_label_cnt]:
205            lval.value = '1'
206
207        return labels
208   
209#########################################################################################
210# Test the code, run from DOS prompt
211# assume the data file is in proper directory
212
213if __name__ == "__main__":
214    data = Orange.data.Table("emotions.tab")
215
216    classifier = Orange.multilabel.BRkNNLearner(data,5)
217    for i in range(10):
218        c,p = classifier(data[i],Orange.classification.Classifier.GetBoth)
219        print c,p
Note: See TracBrowser for help on using the repository browser.