【问题标题】:Tensorflow error: Failed to convert object of type <class 'dict'> to TensorTensorflow 错误:无法将 <class 'dict'> 类型的对象转换为张量
【发布时间】:2018-01-08 12:05:29
【问题描述】:

我正在尝试编写一个可以识别手写数字的神经网络。我正在使用 MNIST 数据集和张量流库。目前,我只是在尝试训练网络,但每当我运行它时它都会抛出一个巨大的错误。我是初学者,如果代码看起来不好,我很抱歉。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data", one_hot = True)
numNodesH1 = 600
numNodesH2 = 500
numNodesH3 = 500
numNodesOut = 10
sizeOfBatch = 150

y = tf.placeholder("float")
x = tf.placeholder("float", [None, 784])

def neuralNetwork(value):
    H1 = {'weights': tf.Variable(tf.random_normal([784, numNodesH1])),
         "biases": tf.Variable(tf.random_normal([numNodesH1]))}

    H2 = {'weights': tf.Variable(tf.random_normal([numNodesH1, 
         numNodesH2])),
         "biases": tf.Variable(tf.random_normal([numNodesH2]))}

    H3 = {"weights": tf.Variable(tf.random_normal([numNodesH2, 
    numNodesH3])),
    "biases": tf.Variable(tf.random_normal([numNodesH3]))}

    output = {"weights": tf.Variable(tf.random_normal([numNodesH3, 
    numNodesOut])),
    "biases": tf.Variable(tf.random_normal([numNodesOut]))}

    FinalH1 = tf.add(tf.matmul(value, H1["weights"]), H1["biases"])
    FinalH1 = tf.nn.relu(FinalH1)
    FinalH2 = tf.add(tf.matmul(H1, H2["weights"]), H2["biases"])
    FinalH2 = tf.nn.relu(FinalH2)
    FinalH3 = tf.add(tf.matmul(H2, H3["weights"]), H3["biases"])
    FinalH3 = tf.nn.relu(FinalH3)
    FinalOut = tf.matmul(H3, output["weights"]) + output["biases"]

    return FinalOut

def train(inputdata):
    prediction = neuralNetwork(inputdata)
    cost=tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizingTool = tf.train.AdamOptimizer().minimize(cost)
    epochsNum = 10

    with tf.Session as sess:
        sess.run(tf.global_variables_initializer())

        for i in range(epochsNum):
            lostEpochs = 0
            for o in range(int(mnist.train.num_examples / sizeOfBatch)):
                ex, ey = mnist.train.next_batch(sizeOfBatch)
                _, c = sess.run([optimizer, cost], feed_dict = {x: ex, y: 
                                ey})
                lostEpochs = lostEpochs + c

            print("Epochs completed = ", i, " / ", epochsNum, " epoch loss = 
            ", lostEpochs)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    neuralAccuracy = tf.reduce_mean(tf.cast(correct, "float"))
    print(neuralAccuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

train(x)

每次我运行这段代码时,它都会给我这个错误:

Traceback (most recent call last):
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\tensor_util.py", line 468, in 
make_tensor_proto
str_values = [compat.as_bytes(x) for x in proto_values]
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\tensor_util.py", line 468, in 
<listcomp>
str_values = [compat.as_bytes(x) for x in proto_values]
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\util\compat.py", line 65, in as_bytes
(bytes_or_text,))
TypeError: Expected binary or unicode string, got {'weights': <tf.Variable 
'Variable:0' shape=(784, 600) dtype=float32_ref>, 'biases': <tf.Variable 
'Variable_1:0' shape=(600,) dtype=float32_ref>}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Msi-
\AppData\Local\Programs\Python\Python36\neuralnetworktest.py", line 45, in 
<module>
train(x)
File "C:\Users\Msi-
\AppData\Local\Programs\Python\Python36\neuralnetworktest.py", line 29, in 
train
prediction = neuralNetwork(inputdata)
File "C:\Users\Msi-
\AppData\Local\Programs\Python\Python36\neuralnetworktest.py", line 22, in 
neuralNetwork
FinalH2 = tf.add(tf.matmul(H1, H2["weights"]), H2["biases"])
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\ops\math_ops.py", line 1844, in matmul
a = ops.convert_to_tensor(a, name="a")
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\ops.py", line 836, in convert_to_tensor
as_ref=False)
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\ops.py", line 926, in 
internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\constant_op.py", line 229, in 
_constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\constant_op.py", line 208, in constant
value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "C:\Users\Msi-\AppData\Local\Programs\Python\Python36\lib\site-
packages\tensorflow\python\framework\tensor_util.py", line 472, in 
make_tensor_proto
"supported type." % (type(values), values))
TypeError: Failed to convert object of type <class 'dict'> to Tensor. 
Contents: 
{'weights': <tf.Variable 'Variable:0' shape=(784, 600) dtype=float32_ref>, 
'biases': <tf.Variable 'Variable_1:0' shape=(600,) dtype=float32_ref>}. 
Consider 
casting elements to a supported type.

【问题讨论】:

  • 作为旁注。如果您使用的是标准 NMIST 数据集,则您有 60000 张图像用于训练。现在你有一个巨大的网络,你正在处理大约一百万个(四舍五入)参数。我会检查过度拟合......为什么这么大的网络?仅使用 softmax 函数作为输出,您已经获得了超过 92%...只是说...

标签: tensorflow machine-learning neural-network deep-learning feed-forward


【解决方案1】:

我想你是说

FinalH1 = tf.add(tf.matmul(value, H1["weights"]), H1["biases"])
FinalH1 = tf.nn.relu(FinalH1)
FinalH2 = tf.add(tf.matmul(FinalH1, H2["weights"]), H2["biases"])
FinalH2 = tf.nn.relu(FinalH2)
FinalH3 = tf.add(tf.matmul(FinalH2, H3["weights"]), H3["biases"])
FinalH3 = tf.nn.relu(FinalH3)
FinalOut = tf.matmul(FinalH3, output["weights"]) + output["biases"]

注意FinalH1 而不是H1H2H3 也是如此。

【讨论】:

  • 现在它显示: Traceback(最近一次调用最后一次):文件“C:\Users\Msi-\AppData\Local\Programs\Python\Python36\neuralnetworktest.py”,第 44 行,在 火车(x)文件“C:\Users\Msi-\AppData\Local\Programs\Python\Python36\neuralnetworktest.py”,第 28 行,在火车预测 = 神经网络(输入数据)文件“C:\Users\Msi -\AppData\Local\Programs\Python\Python36\neuralnetworktest.py",第 20 行,在神经网络 FinalH1 = tf.nn.relu(FinalH1) UnboundLocalError: 分配前引用的局部变量 'FinalH1'
  • 您已删除第一行:FinalH1 = tf.add(tf.matmul(value, H1["weights"]), H1["biases"])。这是正确的,所以我没有将它包含在sn-p中。退货
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 2021-07-09
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 2021-01-05
相关资源
最近更新 更多