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

EnsembleOptimizer._normalize()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
"""Ensemble backend that combines results from multiple projects"""
2
3
4
from hyperopt import hp
5
from tqdm.auto import tqdm
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, metric):
18
        super().__init__(backend, corpus, metric)
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 _normalize(self, hps):
44
        total = sum(hps.values())
45
        return {source: hps[source] / total for source in hps}
46
47
    def _format_cfg_line(self, hps):
48
        return 'sources=' + ','.join([f"{src}:{weight:.4f}"
49
                                      for src, weight in hps.items()])
50
51
    def _test(self, hps):
52
        batch = annif.eval.EvaluationBatch(self._backend.project.subjects)
53
        for goldsubj, srchits in zip(self._gold_subjects, self._source_hits):
54
            weighted_hits = []
55
            for project_id, hits in srchits.items():
56
                weighted_hits.append(annif.suggestion.WeightedSuggestion(
57
                    hits=hits, weight=hps[project_id]))
58
            batch.evaluate(
59
                annif.util.merge_hits(
60
                    weighted_hits,
61
                    self._backend.project.subjects),
62
                goldsubj)
63
        results = batch.results()
64
        line = self._format_cfg_line(self._normalize(hps))
65
        metric = self._metric
66
        tqdm.write(f"Trial: {line} # {metric}: {results[metric]:.4f}")
67
        return 1 - results[metric]
68
69
    def _postprocess(self, best, trials):
70
        line = self._format_cfg_line(self._normalize(best))
71
        score = 1 - trials.best_trial['result']['loss']
72
        return hyperopt.HPRecommendation(lines=[line], score=score)
73
74
75
class EnsembleBackend(hyperopt.AnnifHyperoptBackend):
76
    """Ensemble backend that combines results from multiple projects"""
77
    name = "ensemble"
78
79
    def get_hp_optimizer(self, corpus, metric):
80
        return EnsembleOptimizer(self, corpus, metric)
81
82
    def _normalize_hits(self, hits, source_project):
83
        """Hook for processing hits from backends. Intended to be overridden
84
        by subclasses."""
85
        return hits
86
87
    def _suggest_with_sources(self, text, sources):
88
        hits_from_sources = []
89
        for project_id, weight in sources:
90
            source_project = annif.project.get_project(project_id)
91
            hits = source_project.suggest(text)
92
            self.debug(
93
                'Got {} hits from project {}, weight {}'.format(
94
                    len(hits), source_project.project_id, weight))
95
            norm_hits = self._normalize_hits(hits, source_project)
96
            hits_from_sources.append(
97
                annif.suggestion.WeightedSuggestion(
98
                    hits=norm_hits, weight=weight))
99
        return hits_from_sources
100
101
    def _merge_hits_from_sources(self, hits_from_sources, params):
102
        """Hook for merging hits from sources. Can be overridden by
103
        subclasses."""
104
        return annif.util.merge_hits(hits_from_sources, self.project.subjects)
105
106
    def _suggest(self, text, params):
107
        sources = annif.util.parse_sources(params['sources'])
108
        hits_from_sources = self._suggest_with_sources(text, sources)
109
        merged_hits = self._merge_hits_from_sources(hits_from_sources, params)
110
        self.debug('{} hits after merging'.format(len(merged_hits)))
111
        return merged_hits
112
113
    def _train(self, corpus, params):
114
        raise NotSupportedException('Training ensemble model is not possible.')
115