简体   繁体   中英

Keras custom loss function not printing value of tensor

I am writing just a simple loss function in which I have to convert the tensor to numpy array(it's essential). I am just trying to print value of the tensor but I am getting this error:-

Tensor("loss/activation_4_loss/Print:0", shape=(?, 224, 224, 2), dtype=float32)

def Lc(y_true, y_pred):
    x=K.print_tensor(y_pred)
    print(x)
    return K.mean(y_pred)

Kindly tell me that how can I get the value(numerics) from the tensor? I also tried "eval" but it also threw a big fat error about no session is there and it is a placeholder etc. The whole program is executing fine, just " print_tensor " line is causing problem.

The print statement is redundant. print_tensor will already print the values.

From the documentation of print_tensor:

"Note that print_tensor returns a new tensor identical to x which should be used in the following code. Otherwise the print operation is not taken into account during evaluation ."

In the code above, since y_pred was assigned to x and x was no longer used, the print failed.

Use the version below.

def Lc(y_true, y_pred):
    y_pred=K.print_tensor(y_pred)
    return K.mean(y_pred)

def cat_loss(y_true, y_pred):
    y_pred = K.print_tensor(y_pred)
    return K.categorical_crossentropy(y_true, y_pred)

After I put this cat_loss function in my training loop, I can see the output like this:

[[0.000191014129 0.230871275 0.43813318]...]

190/255 [=====================>........] - ETA: 0s - loss: 0.3442 - acc: 0.9015

[[3.16367514e-05 1.70419597e-07 0.000147014405]...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM