Passed
Push — update-dependencies-v1.0-keras... ( 4886e0 )
by Osma
03:59
created

NNEnsembleBackend.initialize()   B

Complexity

Conditions 5

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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