Passed
Pull Request — master (#677)
by Juho
03:06
created

NNEnsembleBackend._merge_hit_sets_from_sources()   A

Complexity

Conditions 1

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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