I have a model that needs customized inference hence I modified the predict_step
method of the tf.keras.Model
class. I want the inference to be modified depending on certain parameters, is there a simple way to have the predict
method receive parameters and pass them to the predict_step
function?
Something like:
class SimpleModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.threshold = None
def call(self, inputs, training=None, mask=None):
return inputs
def predict(self, x, threshold=0.5, *args, **kwargs):
self.threshold = threshold
return super().predict(x, *args, **kwargs)
def predict_step(self, data):
return tf.greater(self(data, training=False), self.threshold)
if __name__ == "__main__":
x = tf.convert_to_tensor([0.0, 0.55, 0.85, 0.9])
model = SimpleModel()
model.predict(x, threshold=0.5)
model.predict(x, threshold=0.75)
The problem with the approach is that since the predict_step
has already been created the threshold does not change.
Update 1:
This seems to work, not sure if it is the best way though:
class SimpleModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.threshold = None
def call(self, inputs, training=None, mask=None):
return inputs
def predict(self, x, threshold=0.5, *args, **kwargs):
self.threshold = threshold
self.predict_function = None
return super().predict(x, *args, **kwargs)
def predict_step(self, data):
return tf.greater(self(data, training=False), self.threshold)
if __name__ == "__main__":
x = tf.convert_to_tensor([0.0, 0.55, 0.85, 0.9])
model = SimpleModel()
pred = model(x)
pred_1 = model.predict(x, threshold=0.5)
pred_2 = model.predict(x, threshold=0.75)
print(pred, pred_1, pred_2, sep="\n")
Update 2:
Following the question I posted here about the predict_step
function running in graph mode it seems other way to solve the problem is setting the self.run_eagerly = True
of the model.
class SimpleModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.run_eagerly = True
self.threshold = None
def call(self, inputs, training=None, mask=None):
return inputs
def predict(self, x, threshold=0.5, *args, **kwargs):
self.threshold = threshold
return super().predict(x, *args, **kwargs)
def predict_step(self, data):
return tf.greater(self(data, training=False), self.threshold)
if __name__ == "__main__":
x = tf.convert_to_tensor([0.0, 0.55, 0.85, 0.9])
model = SimpleModel()
pred_1 = model.predict(x, threshold=0.5)
pred_2 = model.predict(x, threshold=0.75)
print(pred_1, pred_2, sep="\n")
It now works without the use of tf.Variable
(may run slower because of eager mode).