Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement custom MeanLayer in nn_ensemble #500

Merged
merged 1 commit into from
Aug 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions annif/backend/nn_ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from scipy.sparse import csr_matrix, csc_matrix
import joblib
import lmdb
from tensorflow.keras.layers import Input, Dense, Add, Flatten, Lambda, Dropout
from tensorflow.keras.layers import Input, Dense, Add, Flatten, Dropout, Layer
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.utils import Sequence
import tensorflow.keras.backend as K
Expand Down Expand Up @@ -74,6 +74,12 @@ def __len__(self):
return int(np.ceil(self._counter / self._batch_size))


class MeanLayer(Layer):
"""Custom Keras layer that calculates mean values along the 2nd axis."""
def call(self, inputs):
return K.mean(inputs, axis=2)


class NNEnsembleBackend(
backend.AnnifLearningBackend,
ensemble.BaseEnsembleBackend):
Expand Down Expand Up @@ -112,7 +118,8 @@ def initialize(self):
'model file {} not found'.format(model_filename),
backend_id=self.backend_id)
self.debug('loading Keras model from {}'.format(model_filename))
self._model = load_model(model_filename)
self._model = load_model(model_filename,
custom_objects={'MeanLayer': MeanLayer})

def _merge_hits_from_sources(self, hits_from_sources, params):
score_vector = np.array([np.sqrt(hits.as_vector(subjects))
Expand Down Expand Up @@ -140,7 +147,7 @@ def _create_model(self, sources):
kernel_initializer='zeros',
bias_initializer='zeros')(drop_hidden)

mean = Lambda(lambda x: K.mean(x, axis=2))(inputs)
mean = MeanLayer()(inputs)

predictions = Add()([mean, delta])

Expand Down