代码之家  ›  专栏  ›  技术社区  ›  M.Utku

Python tensorflow不可损坏类型错误

  •  0
  • M.Utku  · 技术社区  · 7 年前

    我在Sendex的教程中研究神经网络。这是我的代码——几乎和他一样——但它引发了一个意外的错误。

    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
    
    n_nodes_hl1 = 500
    n_nodes_hl2 = 500
    n_nodes_hl3 = 500
    
    n_classes = 0
    batch_size = 100
    
    x = tf.placeholder('float',[None, 784])
    y = tf.placeholder('float')
    
    def neural_model(impuls):
        hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),
                          'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
        hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                          'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
        hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                          'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
        output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                          'biases':tf.Variable(tf.random_normal([n_classes]))}
    
        l1 = tf.add(tf.matmul(impuls, hidden_1_layer['weights']), hidden_1_layer['biases'])
        l1 = tf.nn.relu(l1)
    
        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases'])
        l2 = tf.nn.relu(l2)
    
        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
        l3 = tf.nn.relu(l3)
    
        output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
    
        return output
    
    def train_neural_network(x):
        global y
        prediction = neural_model(x)
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
        optimizer = tf.train.AdamOptimizer().minimize(cost)
    
        hm_epochs = 10
    
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
    
            for epoch in range(hm_epochs):
                epoch_loss = 0
                for _ in range(int(mnist.train.num_examples/batch_size)):
                    x, y = mnist.train.next_batch(batch_size)
                    _, c = sess.run([optimizer, cost], feed_dict={x:x, y:y})
                    epoch_loss += c
                print('Epoch: ', epoch, 'completed out of', hm_epochs, 'loss: ', epoch_loss)
            correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))
    
            ac = tf.reduce_mean(tf.cast(correct, 'float'))
            print('acc: ', ac.eval({x:mnist.test_images, y:mnist.test_labels}))
    
    train_neural_network(x)
    

    我认为代码的第一部分不是必需的,但不管怎样。它在第53行中提出了这个错误:

        _, c = sess.run([optimizer, cost], feed_dict={x:x, y:y})
    TypeError: unhashable type: 'numpy.ndarray'
    

    在Sendex的教程中,他的代码与它不同,他没有出错——正如我在评论中看到的其他人一样。我有什么问题吗? 我必须做什么?谢谢你的帮助

    **编辑:*我刚刚解决了第一个错误,但现在它引发了这个。。。

    Traceback (most recent call last):
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1323, in _do_call
        return fn(*args)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
        status, run_metadata)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
        c_api.TF_GetCode(self.status.status))
    tensorflow.python.framework.errors_impl.InvalidArgumentError: Reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero
         [[Node: Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](add, concat)]]
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "a.py", line 61, in <module>
        train_neural_network(x)
      File "a.py", line 53, in train_neural_network
        _, c = sess.run([optimizer, cost], feed_dict={x:_x, y:_y})
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 889, in run
        run_metadata_ptr)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1120, in _run
        feed_dict_tensor, options, run_metadata)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1317, in _do_run
        options, run_metadata)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1336, in _do_call
        raise type(e)(node_def, op, message)
    tensorflow.python.framework.errors_impl.InvalidArgumentError: Reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero
         [[Node: Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](add, concat)]]
    
    Caused by op 'Reshape', defined at:
      File "a.py", line 61, in <module>
        train_neural_network(x)
      File "a.py", line 41, in train_neural_network
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/nn_ops.py", line 1776, in softmax_cross_entropy_with_logits
        precise_logits = _flatten_outer_dims(precise_logits)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/nn_ops.py", line 1551, in _flatten_outer_dims
        output = array_ops.reshape(logits, array_ops.concat([[-1], last_dim_size], 0))
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 3938, in reshape
        "Reshape", tensor=tensor, shape=shape, name=name)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
        op_def=op_def)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2956, in create_op
        op_def=op_def)
      File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1470, in __init__
        self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access
    
    InvalidArgumentError (see above for traceback): Reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero
         [[Node: Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](add, concat)]]
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   GPhilo satyendra    7 年前

    您可以定义占位符 x y 在顶部,但在 train_neural_network 您将其重新定义为 numpy.ndarray s(不可散列) x, y = mnist.train.next_batch(batch_size) .

    更改如下:

    _x, _y = mnist.train.next_batch(batch_size)
    _, c = sess.run([optimizer, cost], feed_dict={x:_x, y:_y})
    

    问题应该解决了。

        2
  •  0
  •   MeadowMuffins    4 年前

    至于第二个 InvalidArgumentError ,您需要更改

    n_classes = 0 n_classes = 10 ,

    否则重塑 prediction 大小为(100,0)到(100,10)的会导致错误。

    也是a learning_rate=0.05 hm_epochs=10 准确率接近89%。