Skip to content

Instantly share code, notes, and snippets.

Last active Mar 26, 2019
What would you like to do?
class BertLayer(tf.layers.Layer):
def __init__(self, n_fine_tune_layers=10, **kwargs):
self.n_fine_tune_layers = n_fine_tune_layers
self.trainable = True
self.output_size = 768
super(BertLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.bert = hub.Module(
trainable_vars = self.bert.variables
# Remove unused layers
trainable_vars = [var for var in trainable_vars if not "/cls/" in]
# Select how many layers to fine tune
trainable_vars = trainable_vars[-self.n_fine_tune_layers :]
# Add to trainable weights
for var in trainable_vars:
# Add non-trainable weights
for var in self.bert.variables:
if var not in self._trainable_weights:
super(BertLayer, self).build(input_shape)
def call(self, inputs):
inputs = [K.cast(x, dtype="int32") for x in inputs]
input_ids, input_mask, segment_ids = inputs
bert_inputs = dict(
input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids
result = self.bert(inputs=bert_inputs, signature="tokens", as_dict=True)[
return result
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment