Passed
Pull Request — master (#414)
by Osma
02:12
created

EnsembleOptimizer.__init__()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 3
1
"""Ensemble backend that combines results from multiple projects"""
2
3
4
import collections
5
from hyperopt import hp
6
import annif.suggestion
7
import annif.project
8
import annif.util
9
import annif.eval
10
from . import hyperopt
11
from annif.exception import NotSupportedException
12
13
14
class EnsembleOptimizer(hyperopt.HyperparameterOptimizer):
15
    """Hyperparameter optimizer for the ensemble backend"""
16
17
    def __init__(self, backend, corpus):
18
        super().__init__(backend, corpus)
19
        self._sources = [project_id for project_id, _
20
                         in annif.util.parse_sources(
21
                             backend.config_params['sources'])]
22
23
    def get_hp_space(self):
24
        space = {}
25
        for project_id in self._sources:
26
            space[project_id] = hp.uniform(project_id, 0.0, 1.0)
27
        return space
28
29
    def _prepare(self):
30
        self._gold_subjects = []
31
        self._source_hits = []
32
33
        for doc in self._corpus.documents:
34
            self._gold_subjects.append(
35
                annif.corpus.SubjectSet((doc.uris, doc.labels)))
36
            srchits = {}
37
            for project_id in self._sources:
38
                source_project = annif.project.get_project(project_id)
39
                hits = source_project.suggest(doc.text)
40
                srchits[project_id] = hits
41
            self._source_hits.append(srchits)
42
43
    def _test(self, hps):
44
        batch = annif.eval.EvaluationBatch(self._backend.project.subjects)
45
        for goldsubj, srchits in zip(self._gold_subjects, self._source_hits):
46
            weighted_hits = []
47
            for project_id, hits in srchits.items():
48
                weighted_hits.append(annif.suggestion.WeightedSuggestion(
49
                    hits=hits, weight=hps[project_id]))
50
            batch.evaluate(
51
                annif.util.merge_hits(
52
                    weighted_hits,
53
                    self._backend.project.subjects),
54
                goldsubj)
55
        results = batch.results()
56
        return 1 - results['NDCG']
57
58
59
class EnsembleBackend(hyperopt.AnnifHyperoptBackend):
60
    """Ensemble backend that combines results from multiple projects"""
61
    name = "ensemble"
62
63
    def get_hp_optimizer(self, corpus):
64
        return EnsembleOptimizer(self, corpus)
65
66
    def _normalize_hits(self, hits, source_project):
67
        """Hook for processing hits from backends. Intended to be overridden
68
        by subclasses."""
69
        return hits
70
71
    def _suggest_with_sources(self, text, sources):
72
        hits_from_sources = []
73
        for project_id, weight in sources:
74
            source_project = annif.project.get_project(project_id)
75
            hits = source_project.suggest(text)
76
            self.debug(
77
                'Got {} hits from project {}, weight {}'.format(
78
                    len(hits), source_project.project_id, weight))
79
            norm_hits = self._normalize_hits(hits, source_project)
80
            hits_from_sources.append(
81
                annif.suggestion.WeightedSuggestion(
82
                    hits=norm_hits, weight=weight))
83
        return hits_from_sources
84
85
    def _merge_hits_from_sources(self, hits_from_sources, params):
86
        """Hook for merging hits from sources. Can be overridden by
87
        subclasses."""
88
        return annif.util.merge_hits(hits_from_sources, self.project.subjects)
89
90
    def _suggest(self, text, params):
91
        sources = annif.util.parse_sources(params['sources'])
92
        hits_from_sources = self._suggest_with_sources(text, sources)
93
        merged_hits = self._merge_hits_from_sources(hits_from_sources, params)
94
        self.debug('{} hits after merging'.format(len(merged_hits)))
95
        return merged_hits
96
97
    def _train(self, corpus, params):
98
        raise NotSupportedException('Training ensemble model is not possible.')
99