Passed
Pull Request — master (#677)
by Juho
07:01
created

NNEnsembleBackend._suggest_batch_with_sources()   A

Complexity

Conditions 2

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nop 3
dl 0
loc 17
rs 9.75
c 0
b 0
f 0
1
"""Neural network based ensemble backend that combines results from multiple
2
projects."""
3
4
5
import os.path
6
import shutil
7
from io import BytesIO
8
9
import joblib
10
import lmdb
11
import numpy as np
12
import tensorflow.keras.backend as K
13
from scipy.sparse import csc_matrix, csr_matrix
14
from tensorflow.keras.layers import Add, Dense, Dropout, Flatten, Input, Layer
15
from tensorflow.keras.models import Model, load_model
16
from tensorflow.keras.utils import Sequence
17
18
import annif.corpus
19
import annif.parallel
20
import annif.util
21
from annif.exception import NotInitializedException, NotSupportedException
22
from annif.suggestion import VectorSuggestionResult
23
24
from . import backend, ensemble
25
26
27
def idx_to_key(idx):
28
    """convert an integer index to a binary key for use in LMDB"""
29
    return b"%08d" % idx
30
31
32
def key_to_idx(key):
33
    """convert a binary LMDB key to an integer index"""
34
    return int(key)
35
36
37
class LMDBSequence(Sequence):
38
    """A sequence of samples stored in a LMDB database."""
39
40
    def __init__(self, txn, batch_size):
41
        self._txn = txn
42
        cursor = txn.cursor()
43
        if cursor.last():
44
            # Counter holds the number of samples in the database
45
            self._counter = key_to_idx(cursor.key()) + 1
46
        else:  # empty database
47
            self._counter = 0
48
        self._batch_size = batch_size
49
50
    def add_sample(self, inputs, targets):
51
        # use zero-padded 8-digit key
52
        key = idx_to_key(self._counter)
53
        self._counter += 1
54
        # convert the sample into a sparse matrix and serialize it as bytes
55
        sample = (csc_matrix(inputs), csr_matrix(targets))
56
        buf = BytesIO()
57
        joblib.dump(sample, buf)
58
        buf.seek(0)
59
        self._txn.put(key, buf.read())
60
61
    def __getitem__(self, idx):
62
        """get a particular batch of samples"""
63
        cursor = self._txn.cursor()
64
        first_key = idx * self._batch_size
65
        cursor.set_key(idx_to_key(first_key))
66
        input_arrays = []
67
        target_arrays = []
68
        for key, value in cursor.iternext():
69
            if key_to_idx(key) >= (first_key + self._batch_size):
70
                break
71
            input_csr, target_csr = joblib.load(BytesIO(value))
72
            input_arrays.append(input_csr.toarray())
73
            target_arrays.append(target_csr.toarray().flatten())
74
        return np.array(input_arrays), np.array(target_arrays)
75
76
    def __len__(self):
77
        """return the number of available batches"""
78
        return int(np.ceil(self._counter / self._batch_size))
79
80
81
class MeanLayer(Layer):
82
    """Custom Keras layer that calculates mean values along the 2nd axis."""
83
84
    def call(self, inputs):
85
        return K.mean(inputs, axis=2)
86
87
88
class NNEnsembleBackend(backend.AnnifLearningBackend, ensemble.BaseEnsembleBackend):
89
    """Neural network ensemble backend that combines results from multiple
90
    projects"""
91
92
    name = "nn_ensemble"
93
94
    MODEL_FILE = "nn-model.h5"
95
    LMDB_FILE = "nn-train.mdb"
96
97
    DEFAULT_PARAMETERS = {
98
        "nodes": 100,
99
        "dropout_rate": 0.2,
100
        "optimizer": "adam",
101
        "epochs": 10,
102
        "learn-epochs": 1,
103
        "lmdb_map_size": 1024 * 1024 * 1024,
104
    }
105
106
    # defaults for uninitialized instances
107
    _model = None
108
109
    def default_params(self):
110
        params = backend.AnnifBackend.DEFAULT_PARAMETERS.copy()
111
        params.update(self.DEFAULT_PARAMETERS)
112
        return params
113
114
    def initialize(self, parallel=False):
115
        super().initialize(parallel)
116
        if self._model is not None:
117
            return  # already initialized
118
        if parallel:
119
            # Don't load TF model just before parallel execution,
120
            # since it won't work after forking worker processes
121
            return
122
        model_filename = os.path.join(self.datadir, self.MODEL_FILE)
123
        if not os.path.exists(model_filename):
124
            raise NotInitializedException(
125
                "model file {} not found".format(model_filename),
126
                backend_id=self.backend_id,
127
            )
128
        self.debug("loading Keras model from {}".format(model_filename))
129
        self._model = load_model(
130
            model_filename, custom_objects={"MeanLayer": MeanLayer}
131
        )
132
133
    def _suggest_batch_with_sources(self, texts, sources):
134
        hit_sets_from_sources = []
135
        for project_id, weight in sources:
136
            source_project = self.project.registry.get_project(project_id)
137
            hit_sets = source_project.suggest(texts)
138
            norm_hit_sets = [
139
                self._normalize_hits(hits, source_project) for hits in hit_sets
140
            ]
141
            hit_sets_from_sources.append(
142
                [
143
                    annif.suggestion.WeightedSuggestion(
144
                        hits=norm_hits, weight=weight, subjects=source_project.subjects
145
                    )
146
                    for norm_hits in norm_hit_sets
147
                ]
148
            )
149
        return hit_sets_from_sources
150
151
    def _merge_hits_from_sources(self, hit_sets_from_sources, params):
152
        score_vectors = np.array(
153
            [
154
                [
155
                    np.sqrt(hits.as_vector(len(subjects)))
156
                    * weight
157
                    * len(hit_sets_from_sources)
158
                    for hits, weight, subjects in hits_from_sources
159
                ]
160
                for hits_from_sources in hit_sets_from_sources
161
            ],
162
            dtype=np.float32,
163
        ).transpose(1, 2, 0)
164
        results = self._model(score_vectors).numpy()
165
        return [VectorSuggestionResult(res) for res in results]
166
167
    def _suggest_batch(self, texts, params):
168
        sources = annif.util.parse_sources(params["sources"])
169
        hit_sets_from_sources = self._suggest_batch_with_sources(texts, sources)
170
        merged_hits = self._merge_hits_from_sources(hit_sets_from_sources, params)
171
        return merged_hits
172
173
    def _create_model(self, sources):
174
        self.info("creating NN ensemble model")
175
176
        inputs = Input(shape=(len(self.project.subjects), len(sources)))
177
178
        flat_input = Flatten()(inputs)
179
        drop_input = Dropout(rate=float(self.params["dropout_rate"]))(flat_input)
180
        hidden = Dense(int(self.params["nodes"]), activation="relu")(drop_input)
181
        drop_hidden = Dropout(rate=float(self.params["dropout_rate"]))(hidden)
182
        delta = Dense(
183
            len(self.project.subjects),
184
            kernel_initializer="zeros",
185
            bias_initializer="zeros",
186
        )(drop_hidden)
187
188
        mean = MeanLayer()(inputs)
189
190
        predictions = Add()([mean, delta])
191
192
        self._model = Model(inputs=inputs, outputs=predictions)
193
        self._model.compile(
194
            optimizer=self.params["optimizer"],
195
            loss="binary_crossentropy",
196
            metrics=["top_k_categorical_accuracy"],
197
        )
198
        if "lr" in self.params:
199
            self._model.optimizer.learning_rate.assign(float(self.params["lr"]))
200
201
        summary = []
202
        self._model.summary(print_fn=summary.append)
203
        self.debug("Created model: \n" + "\n".join(summary))
204
205
    def _train(self, corpus, params, jobs=0):
206
        sources = annif.util.parse_sources(self.params["sources"])
207
        self._create_model(sources)
208
        self._fit_model(
209
            corpus,
210
            epochs=int(params["epochs"]),
211
            lmdb_map_size=int(params["lmdb_map_size"]),
212
            n_jobs=jobs,
213
        )
214
215
    def _corpus_to_vectors(self, corpus, seq, n_jobs):
216
        # pass corpus through all source projects
217
        sources = dict(annif.util.parse_sources(self.params["sources"]))
218
219
        # initialize the source projects before forking, to save memory
220
        self.info(f"Initializing source projects: {', '.join(sources.keys())}")
221
        for project_id in sources.keys():
222
            project = self.project.registry.get_project(project_id)
223
            project.initialize(parallel=True)
224
225
        psmap = annif.parallel.ProjectSuggestMap(
226
            self.project.registry,
227
            list(sources.keys()),
228
            backend_params=None,
229
            limit=None,
230
            threshold=0.0,
231
        )
232
233
        jobs, pool_class = annif.parallel.get_pool(n_jobs)
234
235
        self.info("Processing training documents...")
236
        with pool_class(jobs) as pool:
237
            for hits, subject_set in pool.imap_unordered(
238
                psmap.suggest, corpus.documents
239
            ):
240
                doc_scores = []
241
                for project_id, p_hits in hits.items():
242
                    vector = p_hits.as_vector(len(self.project.subjects))
243
                    doc_scores.append(
244
                        np.sqrt(vector) * sources[project_id] * len(sources)
245
                    )
246
                score_vector = np.array(doc_scores, dtype=np.float32).transpose()
247
                true_vector = subject_set.as_vector(len(self.project.subjects))
248
                seq.add_sample(score_vector, true_vector)
249
250
    def _open_lmdb(self, cached, lmdb_map_size):
251
        lmdb_path = os.path.join(self.datadir, self.LMDB_FILE)
252
        if not cached and os.path.exists(lmdb_path):
253
            shutil.rmtree(lmdb_path)
254
        return lmdb.open(lmdb_path, map_size=lmdb_map_size, writemap=True)
255
256
    def _fit_model(self, corpus, epochs, lmdb_map_size, n_jobs=1):
257
        env = self._open_lmdb(corpus == "cached", lmdb_map_size)
258
        if corpus != "cached":
259
            if corpus.is_empty():
260
                raise NotSupportedException(
261
                    "Cannot train nn_ensemble project with no documents"
262
                )
263
            with env.begin(write=True, buffers=True) as txn:
264
                seq = LMDBSequence(txn, batch_size=32)
265
                self._corpus_to_vectors(corpus, seq, n_jobs)
266
        else:
267
            self.info("Reusing cached training data from previous run.")
268
        # fit the model using a read-only view of the LMDB
269
        self.info("Training neural network model...")
270
        with env.begin(buffers=True) as txn:
271
            seq = LMDBSequence(txn, batch_size=32)
272
            self._model.fit(seq, verbose=True, epochs=epochs)
273
274
        annif.util.atomic_save(self._model, self.datadir, self.MODEL_FILE)
275
276
    def _learn(self, corpus, params):
277
        self.initialize()
278
        self._fit_model(
279
            corpus, int(params["learn-epochs"]), int(params["lmdb_map_size"])
280
        )
281