I am implementing own Keras loss function. How can I access tensor values?
What I\'ve tried
def loss_fn(y_true, y_pred):
print y_true
to print the value of a tensor you need the tensor to have value for example:
import tensorflow as tf
aa = tf.constant([1,5,3])
bb = keras.layers.Dense(4, name="my_tensor")
print('aa:',aa)
print('bb:',bb)
aa: tf.Tensor([1 5 3], shape=(3,), dtype=int32)
bb:
if i want to print b I need to give him a input like this:
aa = tf.constant([[1,5,3]])
bb = keras.layers.Dense(4, name="my_tensor")
print('bb.weights before a assign:',bb.weights,'\n')
print('bb:',bb(aa),'\n')
print('bb.weights:',bb.weights)
Output:
bb.weight before a assign: []
bb: tf.Tensor([[1.0374807 3.4536252 1.5064619 2.1762671]], shape=(1, 4), dtype=float32)
bb.weight: [, ]
If bb is a tensor inside a model or a tensor that the size of the input is fix this will not work
inputs = keras.Input(shape=(3,), name="inputs")
b = keras.layers.Dense(4, name="my_tensor")(inputs)
a = tf.constant([[1,5,3]])
print('b:',b(a),'\n')
Output:
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable
i use feature_extractor to fix it:
inputs = keras.Input(shape=(3,), name="inputs")
bb = keras.layers.Dense(4, name="my_tensor")(inputs)
feature_extractor = keras.Model(
inputs=inputs,
outputs=bb,
)
aa = tf.constant([[1,5,3]])
print('feature_extractor:',feature_extractor(aa),'\n')
Output:
feature_extractor: tf.Tensor([[-4.9181094 4.956725 -1.8055304 2.6975303]], shape=(1, 4), dtype=float32)