简体   繁体   English

InvalidArgumentError:您必须使用 dtype float 和 shape 为占位符张量“Placeholder”提供一个值

[英]InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape

I have written the following code in my Pycharm which does Fully Connect Layer (FCL) in Tensorflow.我在我的 Pycharm 中编写了以下代码,它在 Tensorflow 中执行完全连接层(FCL)。 The placeholder happens invalid argument error.占位符发生无效参数错误。 So I entered all the dtype , shape , and name in the placeholder, but I still get invalid argument error .所以我在占位符中输入了所有dtypeshapename ,但我仍然得到invalid argument error

I want to make new Signal(1, 222) through FCL model.我想通过 FCL 模型制作新的 Signal(1, 222)。
input Signal(1, 222) => output Signal(1, 222)输入信号(1, 222) => 输出信号(1, 222)

  • maxPredict : Find the index with the highest value in the output signal. maxPredict :查找输出信号中具有最高值的索引。
  • calculate Y : Get the frequency array value corresponding to maxPredict. calculate Y :获取 maxPredict 对应的频率数组值。
  • loss : Use the difference between true Y and calculate Y as a loss. loss :使用真实 Y 之间的差值并将 Y 计算为损失。
  • loss = tf.abs(trueY - calculateY)` loss = tf.abs(trueY - calculateY)`

Code (occur Error)代码(发生错误)
x = tf.placeholder(dtype=tf.float32, shape=[1, 222], name='inputX')

ERROR错误

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'inputX' with dtype float and shape [1,222] tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'inputX' with dtype float and shape [1,222] [[{{node inputX}} = Placeholderdtype=DT_FLOAT, shape=[1,222], _device="/job:localhost/replica:0/task:0/device:CPU:0"]] During handling of the above exception, another exception occurred: InvalidArgumentError(参见上面的回溯):您必须为占位符张量“inputX”提供一个值,其 dtype 为 float 和 shape [1,222] tensorflow.python.framework.errors_impl.InvalidArgumentError:您必须为占位符张量“inputX”提供一个值与 dtype float 和 shape [1,222] [[{{node inputX}} = Placeholderdtype=DT_FLOAT, shape=[1,222], _device="/job:localhost/replica:0/task:0/device:CPU:0"]] 期间处理上述异常,又出现了一个异常:

New Error Case新的错误案例

I changed my Code.我改变了我的代码。
x = tf.placeholder(tf.float32, [None, 222], name='inputX')

Error Case 1错误案例一
tensorFreq = tf.convert_to_tensor(basicFreq, tf.float32)
newY = tf.gather(tensorFreq, maxPredict) * 60
loss = tf.abs(y - tf.Variable(newY))

ValueError: initial_value must have a shape specified: Tensor("mul:0", shape=(?,), dtype=float32) ValueError:initial_value 必须具有指定的形状:Tensor("mul:0", shape=(?,), dtype=float32)

Error Case 2错误案例 2
tensorFreq = tf.convert_to_tensor(basicFreq, tf.float32)
newY = tf.gather(tensorFreq, maxPredict) * 60
loss = tf.abs(y - newY)

Traceback (most recent call last): File "D:/PycharmProject/DetectionSignal/TEST_FCL_StackOverflow.py", line 127, in trainStep = opt.minimize(loss) File "C:\Users\Heewony\Anaconda3\envs\TSFW_pycharm\lib\site-packages\tensorflow\python\training\optimizer.py", line 407, in minimize ([str(v) for _, v in grads_and_vars], loss)) ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients , between variables [tf.Variable 'Variable:0' shape=(222, 1024) dtype=float32_ref, tf.Variable 'Variable_1:0' shape=(1024,) dtype=float32_re, ......... tf.Variable 'Variable_5:0' shape=(222,) dtype=float32_ref] and loss Tensor("Abs:0", dtype=float32) . Traceback(最近一次调用最后一次):文件“D:/PycharmProject/DetectionSignal/TEST_FCL_StackOverflow.py”,第 127 行,在 trainStep = opt.minimize(loss) 文件“C:\Users\Heewony\Anaconda3\envs\TSFW_pycharm\lib \site-packages\tensorflow\python\training\optimizer.py",第 407 行,in minimum ([str(v) for _, v in grads_and_vars], loss)) ValueError: No gradients provided for any variable, check your graph对于不支持渐变的操作,在变量之间 [tf.Variable 'Variable:0' shape=(222, 1024) dtype=float32_ref, tf.Variable 'Variable_1:0' shape=(1024,) dtype=float32_re, .. ....... tf.Variable 'Variable_5:0' shape=(222,) dtype=float32_ref] 和loss Tensor("Abs:0", dtype=float32)

Development environment开发环境

  • OS Platform and Distribution: Windows 10 x64操作系统平台和分发:Windows 10 x64
  • TensorFlow installed from: Anaconda TensorFlow 安装自:Anaconda
  • Tensorflow version 1.12.0: TensorFlow 1.12.0 版:
  • python 3.6.7 :蟒蛇3.6.7:
  • Mobile device: N/A移动设备:不适用
  • Exact command to reproduce: N/A重现的确切命令:N/A
  • GPU model and memory: NVIDIA GeForce CTX 1080 Ti GPU型号和内存:NVIDIA GeForce CTX 1080 Ti
  • CUDA/cuDNN: 9.0/7.4 CUDA/cuDNN:9.0/7.4

Model and Function型号与功能

def Model_FCL(inputX):
    data = inputX  # input Signals

    # Fully Connected Layer 1
    flatConvh1 = tf.reshape(data, [-1, 222])
    fcW1 = tf.Variable(tf.truncated_normal(shape=[222, 1024], stddev=0.05))
    fcb1 = tf.Variable(tf.constant(0.1, shape=[1024]))
    fch1 = tf.nn.relu(tf.matmul(flatConvh1, fcW1) + fcb1)

    # Fully Connected Layer 2
    flatConvh2 = tf.reshape(fch1, [-1, 1024])
    fcW2 = tf.Variable(tf.truncated_normal(shape=[1024, 1024], stddev=0.05))
    fcb2 = tf.Variable(tf.constant(0.1, shape=[1024]))
    fch2 = tf.nn.relu(tf.matmul(flatConvh2, fcW2) + fcb2)

    # Output Layer
    fcW3 = tf.Variable(tf.truncated_normal(shape=[1024, 222], stddev=0.05))
    fcb3 = tf.Variable(tf.constant(0.1, shape=[222]))

    logits = tf.add(tf.matmul(fch2, fcW3), fcb3)
    predictY = tf.nn.softmax(logits)
    return predictY, logits

def loadMatlabData(fileName):
    contentsMat = sio.loadmat(fileName)
    dataInput = contentsMat['dataInput']
    dataLabel = contentsMat['dataLabel']

    dataSize = dataInput.shape
    dataSize = dataSize[0]
    return dataInput, dataLabel, dataSize

def getNextSignal(num, data, labels, WINDOW_SIZE, OUTPUT_SIZE):
    shuffleSignal = data[num]
    shuffleLabels = labels[num]

    # shuffleSignal = shuffleSignal.reshape(1, WINDOW_SIZE)
    # shuffleSignal = np.asarray(shuffleSignal, np.float32)
    return shuffleSignal, shuffleLabels

def getBasicFrequency():
    # basicFreq => shape(222)
    basicFreq = np.array([0.598436736688, 0.610649731314, ... 3.297508549096])
    return basicFreq

Graph图形

basicFreq = getBasicFrequency()
myGraph = tf.Graph()
with myGraph.as_default():
    # define input data & output data 입력받기 위한 placeholder
    x = tf.placeholder(dtype=tf.float32, shape=[1, 222], name='inputX') # Signal size = [1, 222]
    y = tf.placeholder(tf.float32, name='trueY') # Float value size = [1]

    print('inputzz ', x, y)
    print('Graph  ', myGraph.get_operations())
    print('TrainVariable ', tf.trainable_variables())

    predictY, logits = Model_FCL(x) # Predict Signal, size = [1, 222]
    maxPredict = tf.argmax(predictY, 1, name='maxPredict') # Find max index of Predict Signal

    tensorFreq = tf.convert_to_tensor(basicFreq, tf.float32)
    newY = tf.gather(tensorFreq, maxPredict) * 60   # Find the value that corresponds to the Freq array index
    loss = tf.abs(y - tf.Variable(newY))  # Calculate absolute (true Y - predict Y)
    opt = tf.train.AdamOptimizer(learning_rate=0.0001)
    trainStep = opt.minimize(loss)

    print('Graph  ', myGraph.get_operations())
    print('TrainVariable ', tf.trainable_variables())  

Session会议

with tf.Session(graph=myGraph) as sess:
    sess.run(tf.global_variables_initializer())

    dataFolder = './'
    writer = tf.summary.FileWriter('./logMyGraph', sess.graph)
    startTime = datetime.datetime.now()

    numberSummary = 0
    accuracyTotalTrain = []
    for trainEpoch in range(1, 25 + 1):
        arrayTrain = []

        dataPPG, dataLabel, dataSize = loadMatlabData(dataFolder + "TestValues.mat")

        for i in range(dataSize):
            batchSignal, valueTrue = getNextSignal(i, dataPPG, dataLabel, 222, 222)
            _, lossPrint, valuePredict = sess.run([trainStep, loss, newY], feed_dict={x: batchSignal, y: valueTrue})
            print('Train ', i, ' ', valueTrue, ' - ', valuePredict, '   Loss ', lossPrint)

            arrayTrain.append(lossPrint)
            writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag='Loss', simple_value=float(lossPrint))]),
                               numberSummary)
            numberSummary += 1
        accuracyTotalTrain.append(np.mean(arrayTrain))
    print('Final Train : ', accuracyTotalTrain)

    sess.close()    

It seems that the variable batchSignal is of a wrong type or shape.似乎变量batchSignal的类型或形状错误。 It must be a numpy array of shape exactly [1, 222] .它必须是一个形状正好为[1, 222]的 numpy 数组。 If you want to use a batch of examples of size n × 222, the placeholder x should have a shape of [None, 222] and placeholder y shape [None] .如果要使用一批大小为n × 222 的示例,则占位符x的形状应为[None, 222] ,占位符y的形状为[None]

By the way, consider using tf.layers.dense instead of explicitly initializing variables and implementing the layers yourself.顺便说一句,考虑使用tf.layers.dense而不是显式初始化变量并自己实现层。

There should be two things to change.应该有两点改变。

Error Case 0. You don't need to reshape your flow between layers.错误案例 0。您不需要重塑层之间的流程。 You can use None at the first dimension to pass a dynamic batch size.您可以在第一个维度使用None来传递动态批量大小。

Error Case 1. You can use directly your newY as output of the NN.错误案例 1。您可以直接使用 newY 作为 NN 的输出。 You only use tf.Variable to define weights or bias.您只使用 tf.Variable 来定义权重或偏差。

Error Case 2. And it seems that tensorflow doesn't have gradient descent implementation for neither tf.abs() nor tf.gather() .错误案例 2。似乎 tensorflow 对于tf.abs()tf.gather()都没有梯度下降实现。 With a regression problem, the mean square error is often sufficient.对于回归问题,均方误差通常就足够了。

Herein, how I rewrite your code.在这里,我如何重写你的代码。 I don't have your matlab part so I can't debug your python/matlab interface:我没有你的 matlab 部分,所以我无法调试你的 python/matlab 接口:

Model:模型:

def Model_FCL(inputX):
    # Fully Connected Layer 1
    fcW1 = tf.get_variable('w1', shape=[222, 1024], initializer=tf.initializer.truncated_normal())
    fcb1 = tf.get_variable('b1', shape=[222], initializer=tf.initializer.truncated_normal())
    # fcb1 = tf.get_variable('b1', shape=[None, 222], trainable=False, initializer=tf.constant_initializer(valueThatYouWant)) # if you want to fix your bias constant
    fch1 = tf.nn.relu(tf.matmul(inputX, fcW1) + fcb1, name='relu1')

    # Fully Connected Layer 2
    fcW2 = tf.get_variable('w2', shape=[1024, 1024], initializer=tf.initializer.truncated_normal())
    fcb2 = tf.get_variable('b2', shape=[222], initializer=tf.initializer.truncated_normal())
    # fcb2 = tf.get_variable('b2', shape=[None, 222], trainable=False, initializer=tf.constant_initializer(valueThatYouWant)) # if you want to fix your bias constant
    fch2 = tf.nn.relu(tf.matmul(fch1, fcW2) + fcb2, name='relu2')

    # Output Layer
    fcW3 = tf.get_variable('w3', shape=[1024, 222], initializer=tf.initializer.truncated_normal())
    fcb3 = tf.get_variable('b3', shape=[222], initializer=tf.initializer.truncated_normal())
    # fcb2 = tf.get_variable('b2', shape=[None, 222], trainable=False, initializer=tf.constant_initializer(valueThatYouWant)) # if you want to fix your bias constant
    logits = tf.add(tf.matmul(fch2, fcW3), fcb3)

    predictY = tf.nn.softmax(logits)  #I'm not sure that it will learn if you do softmax then abs/MSE
    return predictY, logits

Graph:图形:

with myGraph.as_default():
    # define input data & output data 입력받기 위한 placeholder
    # put None(dynamic batch size) not -1 at the first dimension so that you can change your batch size
    x = tf.placeholder(tf.float32, shape=[None, 222], name='inputX')  # Signal size = [1, 222]
    y = tf.placeholder(tf.float32, shape=[None], name='trueY')  # Float value size = [1]

    ...

    predictY, logits = Model_FCL(x)  # Predict Signal, size = [1, 222]
    maxPredict = tf.argmax(predictY, 1, name='maxPredict')  # Find max index of Predict Signal

    tensorFreq = tf.convert_to_tensor(basicFreq, tf.float32)
    newY = tf.gather(tensorFreq, maxPredict) * 60   # Find the value that corresponds to the Freq array index

    loss = tf.losses.mean_squared_error(labels=y, predictions=newY)  # maybe use MSE for regression problem
    # loss = tf.abs(y - newY)  # Calculate absolute (true Y - predict Y) #tensorflow doesn't have gradient descent implementation for tf.abs
    opt = tf.train.AdamOptimizer(learning_rate=0.0001)
    trainStep = opt.minimize(loss)

If you are still getting the same error even after feeding the right numpy shape and also maintaining the correct dtypes (np.int32 or np.float32) as suggested by the error message, then the following code should solve your problem:如果即使在输入正确的 numpy 形状并按照错误消息的建议保持正确的 dtypes(np.int32 或 np.float32)后仍然出现相同的错误,那么以下代码应该可以解决您的问题:

#this code will print the list of placeholders and other variables declared in the memory which is causing your error
[n.name for n in tf.get_default_graph().as_graph_def().node] 
#it will reset your declared placeholders so you can start over
tf.reset_default_graph()

This problem could also be solved by restarting the kernel repeatedly for each debug however it's not feasible.这个问题也可以通过每次调试重复重新启动内核来解决,但这是不可行的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 InvalidArgumentError:您必须使用dtype float来输入占位符张量'Placeholder'的值 - InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float InvalidArgumentError:您必须使用 dtype float 和 shape [?,?,3] 为占位符张量“Placeholder_1”提供一个值 - InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,?,3] 您必须使用dtype float和shape输入占位符张量'Placeholder'的值 - You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape tensorflow InvalidArgumentError:您必须使用dtype float为占位符张量提供值 - tensorflow InvalidArgumentError: You must feed a value for placeholder tensor with dtype float InvalidArgumentError:您必须使用 dtype float 和 shape 为占位符张量“time_distributed_1_target”提供一个值 - InvalidArgumentError: You must feed a value for placeholder tensor 'time_distributed_1_target' with dtype float and shape InvalidArgumentError:您必须使用dtype float和shape [?,1339,2560,1]输入占位符张量'input_1'的值 - InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,1339,2560,1] InvalidArgumentError:您必须使用 dtype double 为占位符张量“Placeholder”提供一个值 - InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype double InvalidArgumentError:您必须使用dtype float输入占位符张量'Placeholder_109'的值 - InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_109' with dtype float InvalidArgumentError(请参阅上面的回溯):您必须使用dtype float输入占位符张量“ Placeholder_2”的值 - InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float InvalidArgumentError(请参阅上面的回溯):您必须使用dtype float输入占位符张量“ Placeholder”的值 - InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM