Keras 错误 "You must feed a value for placeholder tensor"

Keras error "You must feed a value for placeholder tensor"

我有简单的 seq2seq 模型:

import seq2seq
import numpy as np
import keras.backend as K

from seq2seq.models import Seq2Seq
from keras.models import Model
from keras.models import Sequential
from keras.layers import Embedding, Input, TimeDistributed, Activation

BLOCK_LEN = 60
EVENTS_CNT = 462

input = Input((BLOCK_LEN,))
embedded = Embedding(input_dim=EVENTS_CNT+1, output_dim=200)(input)
emb_model = Model(input, embedded)

seq_model = Seq2Seq(batch_input_shape=(None, BLOCK_LEN, 200), hidden_dim=200, output_length=BLOCK_LEN, output_dim=EVENTS_CNT)
model = Sequential()
model.add(emb_model)
model.add(seq_model)
model.add(TimeDistributed(Activation('softmax')))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
model_1 (Model)              (None, 60, 200)           92600     
_________________________________________________________________
model_12 (Model)             (None, 60, 462)           1077124   
_________________________________________________________________
time_distributed_2 (TimeDist (None, 60, 462)           0         
=================================================================
Total params: 1,169,724
Trainable params: 1,169,724
Non-trainable params: 0
_________________________________________________________________

我正在尝试创建自己的指标:

def symbol_acc(true, predicted):
    np_y_true = K.get_value(true)
    np_y_pred = K.get_value(predicted)
    return K.mean(np_y_true == np_y_pred)

如果我尝试使用此指标编译模型,我会收到错误 "You must feed a value for placeholder tensor",并显示以下消息:

InvalidArgumentError                      Traceback (most recent call last)
C:\Users\Anna\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1322     try:
-> 1323       return fn(*args)
   1324     except errors.OpError as e:

C:\Users\Anna\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1301                                    feed_dict, fetch_list, target_list,
-> 1302                                    status, run_metadata)
   1303 

C:\Users\Anna\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
    472             compat.as_text(c_api.TF_Message(self.status.status)),
--> 473             c_api.TF_GetCode(self.status.status))
    474     # Delete the underlying status object from memory otherwise it stays alive

InvalidArgumentError: You must feed a value for placeholder tensor 'time_distributed_2_target' with dtype float and shape [?,?,?]
     [[Node: time_distributed_2_target = Placeholder[dtype=DT_FLOAT, shape=[?,?,?], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

但以下代码运行良好(不会产生任何异常):

def symbol_acc2(true, predicted):
    true = np.array(true)
    predicted = np.array(predicted)
    return K.variable((true == predicted).mean())

你能解释一下这个异常是什么意思吗?我以为 symbol_accsymbol_acc2 在做同样的事情。我是 NNs 和 keras 的新手,所以也许我没有看到一些明显的东西。我在 Whosebug 上看到了类似的问题,但没有找到适合我的情况的答案。

指标、损失和整个模型都是 "symbolic" 个张量。

这意味着,在您开始拟合或预测之前,它们绝对没有数据(或值)。

当您调用 K.get_value 时,您正在尝试获取一个不存在的值。 (只有当你 "feed the data" 到模型时它才会存在。它所谓的占位符是一个空的输入张量,它期望在拟合或预测时接收数据)。

您的问题的解决方案就是不尝试获取值。 (numpy版本也不行,这个函数编译时值不存在)

您必须保持所有操作都是符号化的,它们将在您输入数据时执行。

所以:

def symbol_acc(true, predicted):
    isEqual = K.cast(K.equal(true,predicted),K.floatx())
    return K.mean(isEqual)

symbol_acc 中,非工作版本 tf.keras.backend.get_value() (K.get_value() in your code) will go and fetch the value of a variable as a Numpy array. Then this line K.mean(np_y_true == np_y_pred) first creates another (boolean) Numpy array 基于相等性,而 tf.keras.backend.mean() 试图将 Numpy 数组视为张量,但它不起作用方式。

显示错误是因为在图形创建时 true 还没有值,还没有被提供。

symbol_acc2 不会抛出错误,但也不会起作用,因为在图创建时 truepredicted 只是空张量。 Numpy 不会改变它,但比较会失败,取其平均值将产生零,而你只是创建一个值为零的变量。考虑这段代码(经过测试):

import keras.backend as K
import numpy as np

true = K.placeholder( ( 2, ) )
predicted = K.placeholder( ( 2, ) )
a = np.array( true )
b = np.array( predicted )
c = a == b
print( c, c.mean() )

输出:

(False, 0.0)

不管数据如何(张量中甚至还没有数据。)

为了实现你想要的,即计算预测的准确性,你可以简单地使用

def symbol_acc( true, predicted ):
    return K.mean( K.cast_to_floatx( K.equal( true, predicted ) ) )

或者您可以让自己的生活更轻松,并查看 Keras 自己的 categorical_accuracy 指标。