问题描述
我正在编写一个简单的损失函数,其中我必须将张量转换为numpy数组(这是必不可少的).我只是想打印张量的值,但出现此错误:-
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:-
def Lc(y_true, y_pred):
x=K.print_tensor(y_pred)
print(x)
return K.mean(y_pred)
请告诉我如何从张量中获取值(数字)?我也尝试过"eval",但它也引发了一个严重的错误,即没有会话存在,并且它是一个占位符等.整个程序执行得很好,只是" print_tensor "行引起了问题. /p>
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.
推荐答案
print语句是多余的. print_tensor将已经打印出这些值.
The print statement is redundant. print_tensor will already print the values.
来自print_tensor的文档:
From the documentation of print_tensor:
"请注意,print_tensor
返回与x
相同的新张量 应在以下代码中使用.否则 评估期间不会考虑打印操作."
"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."
在上面的代码中,由于将y_pred分配给x,并且不再使用x,所以打印失败.
In the code above, since y_pred was assigned to x and x was no longer used, the print failed.
使用以下版本.
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)
将这个cat_loss函数放入训练循环后,我可以看到如下输出:
After I put this cat_loss function in my training loop, I can see the output like this:
[[0.000191014129 0.230871275 0.43813318] ...]
[[0.000191014129 0.230871275 0.43813318]...]
190/255 [===================> ........]-ETA:0s-损失:0.3442-acc:0.9015
190/255 [=====================>........] - ETA: 0s - loss: 0.3442 - acc: 0.9015
[[3.16367514e-05 1.70419597e-07 0.000147014405] ...]
[[3.16367514e-05 1.70419597e-07 0.000147014405]...]
这篇关于Keras自定义损失函数不打印张量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!