python - Tensorflow:您必须使用 dtype float 为占位符张量 'Placeholder' 提供一个值 [但该值是一个 float ]

标签 python numpy tensorflow

我正在学习一个 tensorflow 教程并不断收到此错误:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

这是回溯:

Traceback (most recent call last):
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 972, in _do_call
    return fn(*args)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 954, in _run_fn
    status, run_metadata)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/framework/errors.py", line 463, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "neural_network.py", line 48, in <module>
    print(sess.run(loss), feed_dict={xs:x_data, ys:y_data})
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 717, in run
    run_metadata_ptr)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 915, in _run
    feed_dict_string, options, run_metadata)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 965, in _do_run
    target_list, options, run_metadata)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 985, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'Placeholder', defined at:
  File "neural_network.py", line 21, in <module>
    xs = tf.placeholder(tf.float32,[None,1])
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1332, in placeholder
    name=name)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1748, in _placeholder
    name=name)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_op
    op_def=op_def)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2380, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/mddrill/anaconda2/envs/python35/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1298, in __init__
    self._traceback = _extract_stack()

这是我的代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def add_layer(inputs, in_size, out_size,activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# Make up some data
x_data = np.linspace(-1,1,300, dtype=np.float32)[:,np.newaxis]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])

# add hidden layer
lay1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)

#add output layer
prediction = add_layer(lay1, 10, 1, activation_function=None)

# the error between prediction and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))
### if we have [[3,4],[5,6],[7,8]] and reduction_indices is 1
### then we are taking f(3,4) f(5,6) and f(7,8)
### if reduction_indices is 0, then we are taking
### f(3,5,7) and f(4,6,8)
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# important step
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    for i in range(1000):
        # training
        sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
        if i% 50 == 0:
            # to see the step improvement
            print(sess.run(loss), feed_dict={xs:x_data, ys:y_data})

正如您在此处看到的,x_data 和 y_data 都是 float ,所以我不明白为什么会出现此错误。

当我添加打印语句时 print(type(x_data[0][0]),type(y_data[0][0]))就在sess.run(train_step, feed_dict={xs:x_data, ys:y_data})之前.我明白了:<class 'numpy.float32'> <class 'numpy.float32'>很明显他们都是花车

我在这里错过了什么?

最佳答案

您在 print() 语句中有错误。幸运的是,当我使用 TensorFlow r0.11 时,它作为 SyntaxError 为我挑选出来。

替换,

print(sess.run(loss), feed_dict={xs:x_data, ys:y_data})

与,

print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))

关于python - Tensorflow:您必须使用 dtype float 为占位符张量 'Placeholder' 提供一个值 [但该值是一个 float ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414867/

相关文章:

python - 线性回归实现中的问题

python - np.random.seed(int) 和 np.random.seed(array_like) 的区别?

python - 如何获取 numpy 数组中不连续索引的元素?

python - 如何从 tensorflow 中的谷歌存储桶中读取文件?

python - ValueError : Shapes must be equal rank, 但是是 1 和 0 来自将形状 1 与其他形状合并。对于 'loss/AddN'

python - 如何在graphene_django中隐藏/排除请求实体的某些外键字段?

python - 浮点比较不适用于 pandas groupby 输出

python - 类型错误 : string or bytes-like object expected

python - C 和 Python 之间共享变量

python - 如何将 tensorflow 集线器模块保存到自定义路径/从自定义路径加载?