How can I print the values of Keras tensors?

后端 未结 7 1420
梦毁少年i
梦毁少年i 2020-12-14 00:43

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


        
相关标签:
7条回答
  • 2020-12-14 01:36

    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: <tensorflow.python.keras.layers.core.Dense object at 0x000001D4B0137048>
    

    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: [<tf.Variable 'my_tensor/kernel:0' shape=(3, 4) dtype=float32, numpy=
    array([[ 0.885918  , -0.88332534, -0.40944284, -0.04479438],
           [-0.27336687,  0.34549594, -0.11853147,  0.15316617],
           [ 0.50613236,  0.8698236 ,  0.83618736,  0.4850769 ]],
          dtype=float32)>, <tf.Variable 'my_tensor/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>]
    

    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) 
    
    
    
    
    0 讨论(0)
提交回复
热议问题