Passed
Push — issue678-refactor-suggestionre... ( 0d7003...d7e7fa )
by Osma
02:49
created

NNEnsembleBackend._merge_source_batches()   A

Complexity

Conditions 1

Size

Total Lines 21
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nop 4
dl 0
loc 21
rs 9.5
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 SuggestionBatch, vector_to_suggestions
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 _merge_source_batches(self, batch_by_source, sources, params):
134
        src_weight = dict(sources)
135
        score_vectors = np.array(
136
            [
137
                [
138
                    np.sqrt(suggestions.as_vector())
139
                    * src_weight[project_id]
140
                    * len(batch_by_source)
141
                    for suggestions in batch
142
                ]
143
                for project_id, batch in batch_by_source.items()
144
            ],
145
            dtype=np.float32,
146
        ).transpose(1, 2, 0)
147
        prediction = self._model(score_vectors).numpy()
148
        return SuggestionBatch.from_sequence(
149
            [
150
                vector_to_suggestions(row, limit=int(params["limit"]))
151
                for row in prediction
152
            ],
153
            self.project.subjects,
154
        )
155
156
    def _create_model(self, sources):
157
        self.info("creating NN ensemble model")
158
159
        inputs = Input(shape=(len(self.project.subjects), len(sources)))
160
161
        flat_input = Flatten()(inputs)
162
        drop_input = Dropout(rate=float(self.params["dropout_rate"]))(flat_input)
163
        hidden = Dense(int(self.params["nodes"]), activation="relu")(drop_input)
164
        drop_hidden = Dropout(rate=float(self.params["dropout_rate"]))(hidden)
165
        delta = Dense(
166
            len(self.project.subjects),
167
            kernel_initializer="zeros",
168
            bias_initializer="zeros",
169
        )(drop_hidden)
170
171
        mean = MeanLayer()(inputs)
172
173
        predictions = Add()([mean, delta])
174
175
        self._model = Model(inputs=inputs, outputs=predictions)
176
        self._model.compile(
177
            optimizer=self.params["optimizer"],
178
            loss="binary_crossentropy",
179
            metrics=["top_k_categorical_accuracy"],
180
        )
181
        if "lr" in self.params:
182
            self._model.optimizer.learning_rate.assign(float(self.params["lr"]))
183
184
        summary = []
185
        self._model.summary(print_fn=summary.append)
186
        self.debug("Created model: \n" + "\n".join(summary))
187
188
    def _train(self, corpus, params, jobs=0):
189
        sources = annif.util.parse_sources(self.params["sources"])
190
        self._create_model(sources)
191
        self._fit_model(
192
            corpus,
193
            epochs=int(params["epochs"]),
194
            lmdb_map_size=int(params["lmdb_map_size"]),
195
            n_jobs=jobs,
196
        )
197
198
    def _corpus_to_vectors(self, corpus, seq, n_jobs):
199
        # pass corpus through all source projects
200
        sources = dict(annif.util.parse_sources(self.params["sources"]))
201
202
        # initialize the source projects before forking, to save memory
203
        self.info(f"Initializing source projects: {', '.join(sources.keys())}")
204
        for project_id in sources.keys():
205
            project = self.project.registry.get_project(project_id)
206
            project.initialize(parallel=True)
207
208
        psmap = annif.parallel.ProjectSuggestMap(
209
            self.project.registry,
210
            list(sources.keys()),
211
            backend_params=None,
212
            limit=None,
213
            threshold=0.0,
214
        )
215
216
        jobs, pool_class = annif.parallel.get_pool(n_jobs)
217
218
        self.info("Processing training documents...")
219
        with pool_class(jobs) as pool:
220
            for hits, subject_set in pool.imap_unordered(
221
                psmap.suggest, corpus.documents
222
            ):
223
                doc_scores = []
224
                for project_id, p_hits in hits.items():
225
                    vector = p_hits.as_vector()
226
                    doc_scores.append(
227
                        np.sqrt(vector) * sources[project_id] * len(sources)
228
                    )
229
                score_vector = np.array(doc_scores, dtype=np.float32).transpose()
230
                true_vector = subject_set.as_vector(len(self.project.subjects))
231
                seq.add_sample(score_vector, true_vector)
232
233
    def _open_lmdb(self, cached, lmdb_map_size):
234
        lmdb_path = os.path.join(self.datadir, self.LMDB_FILE)
235
        if not cached and os.path.exists(lmdb_path):
236
            shutil.rmtree(lmdb_path)
237
        return lmdb.open(lmdb_path, map_size=lmdb_map_size, writemap=True)
238
239
    def _fit_model(self, corpus, epochs, lmdb_map_size, n_jobs=1):
240
        env = self._open_lmdb(corpus == "cached", lmdb_map_size)
241
        if corpus != "cached":
242
            if corpus.is_empty():
243
                raise NotSupportedException(
244
                    "Cannot train nn_ensemble project with no documents"
245
                )
246
            with env.begin(write=True, buffers=True) as txn:
247
                seq = LMDBSequence(txn, batch_size=32)
248
                self._corpus_to_vectors(corpus, seq, n_jobs)
249
        else:
250
            self.info("Reusing cached training data from previous run.")
251
        # fit the model using a read-only view of the LMDB
252
        self.info("Training neural network model...")
253
        with env.begin(buffers=True) as txn:
254
            seq = LMDBSequence(txn, batch_size=32)
255
            self._model.fit(seq, verbose=True, epochs=epochs)
256
257
        annif.util.atomic_save(self._model, self.datadir, self.MODEL_FILE)
258
259
    def _learn(self, corpus, params):
260
        self.initialize()
261
        self._fit_model(
262
            corpus, int(params["learn-epochs"]), int(params["lmdb_map_size"])
263
        )
264