【问题标题】:Value Error in tensorflow张量流中的值错误
【发布时间】:2018-07-21 05:55:14
【问题描述】:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/temp/data", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

# matrix = height * width
x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')


# defining the neural network

def neural_network_model(data):
    hiddenLayer1 = {'weights': tf.Variable(tf.random_normal([784, n_nodes_hl1])),
                    'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hiddenLayer2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                    'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hiddenLayer3 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                    'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}

    outputLayer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                   'biases': tf.Variable(tf.random_normal([n_classes]))}

    l1 = tf.add(tf.matmul(data, hiddenLayer1['weights']), hiddenLayer1['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hiddenLayer2['weights']), hiddenLayer2['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hiddenLayer3['weights']), hiddenLayer3['biases'])
    l3 = tf.nn.relu(l3)
    output = tf.matmul(l3, outputLayer['weights']), outputLayer['biases']
    return output


# training the network
def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(prediction,tf.squeeze(y)))
    #cost = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)
    #cost = tf.reduce_mean(cost) * 100
    optimizer = tf.train.AdamOptimizer(0.003).minimize(cost)

    # cycles feed forward + backprop
    numberOfEpochs = 10

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

         #dealing with training data
        for epoch in range(numberOfEpochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples / batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += c
            print('Epoch', epoch, ' completed out of ', numberOfEpochs, ' loss: ', epoch_loss)

            correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
            accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
            print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))


train_neural_network(x)

我是 Tensorflow 的新手,我正在尝试训练我的模型来读取数据集。但是每次我运行代码,我都会得到这个错误:

Traceback(最近一次调用最后一次): 文件“firstAI.py”,第 87 行,在 train_neural_network(x) train_neural_network 中的文件“firstAI.py”,第 62 行 成本 = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(预测,tf.squeeze(y))); 文件“/home/phillipus/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py”,第 1935 行,在 sparse_softmax_cross_entropy_with_logits 标签,logits) _ensure_xent_args 中的文件“/home/phillipus/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py”,第 1713 行 "命名参数 (labels=..., logits=..., ...)" % name) ValueError:仅使用命名参数(labels=...、logits=...、...)调用 sparse_softmax_cross_entropy_with_logits

看起来问题出在“cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(prediction,tf.squeeze(y)))”和“ train_neural_network(x)”函数。我是 Tensorflow 的新手,所以我的故障排除不是最好的,有人可以帮助我吗?

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    也许您可以尝试在成本计算中使用 tf.nn.softmax_cross_entropy_with_logits 而不是 tf.nn.sparse_softmax_cross_entropy_with_logits。

    但是,如果您想继续使用 tf.nn.sparse_softmax_cross_entropy_with_logits,那么此链接可能会有所帮助:Tensorflow ValueError: Only call `sparse_softmax_cross_entropy_with_logits` with named arguments。

    顺便问一下,你用的tensorflow和python是什么版本的?

    尝试运行这个:

    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    
    mnist = input_data.read_data_sets("/temp/data", one_hot=True)
    
    n_nodes_hl1 = 500
    n_nodes_hl2 = 500
    n_nodes_hl3 = 500
    
    n_classes = 10
    batch_size = 100
    
    # matrix = height * width
    x = tf.placeholder('float', [None, 784])
    y = tf.placeholder('float')
    
    
    # defining the neural network
    
    def neural_network_model(data):
        hiddenLayer1 = {'weights': tf.Variable(tf.random_normal([784, 
                n_nodes_hl1])),
            'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}
    
        hiddenLayer2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}
    
        hiddenLayer3 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
            'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}
    
        outputLayer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
               'biases': tf.Variable(tf.random_normal([n_classes]))}
    
        l1 = tf.add(tf.matmul(data, hiddenLayer1['weights']), hiddenLayer1['biases'])
        l1 = tf.nn.relu(l1)
    
        l2 = tf.add(tf.matmul(l1, hiddenLayer2['weights']), hiddenLayer2['biases'])
        l2 = tf.nn.relu(l2)
    
        l3 = tf.add(tf.matmul(l2, hiddenLayer3['weights']), hiddenLayer3['biases'])
        l3 = tf.nn.relu(l3)
    
        output = tf.add(tf.matmul(l3, outputLayer['weights']),outputLayer['biases'])
        return output
    
    
    prediction = neural_network_model(x)
    cost = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)
    optimizer = tf.train.AdamOptimizer(0.003).minimize(cost)
    
    # cycles feed forward + backprop
    numberOfEpochs = 10
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
    
         #dealing with training data
        for epoch in range(numberOfEpochs):
        epoch_loss = 0
        for _ in range(int(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
            epoch_loss += c
        print('Epoch', epoch, ' completed out of ', numberOfEpochs, ' loss: ', epoch_loss)
    
        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
        print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
    

    【讨论】:

    • 我的python版本是3.6.3,我的tensorflow版本是1.5.0。我试过你的建议,我得到了同样的错误
    • 试试这条线看看它是否有效:cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=prediction, labels=tf.squeeze(y)))
    • 那么让我们尝试更多组合,希望在某些时候您不会遇到任何错误,然后您可以从那里构建。尝试:cost = (1) tf.nn.sparse_softmax_cross_entropy_with_logits(logits=prediction, labels=y) (2) 在您尝试成本的那一行下方的注释行,它有效吗? (有和没有 tf.squeeze(y))
    • 全部失败,不得不说,这太残酷了
    • 是的!通常情况就是这样。但是您可以运行此代码,不用担心。对于选项 (1),您是否尝试过不使用 tf.reduce_mean 的成本?只是:cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=prediction, labels=y)
    【解决方案2】:

    试试这个代码

    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("/temp/data/", one_hot = True)
    
    n_nodes_hl1 = 500
    n_nodes_hl2 = 500
    n_nodes_hl3 = 500
    
    n_classes = 10
    batch_size = 100
    
    #height x width
    
    x = tf.placeholder('float',[None, 784])
    y = tf.placeholder('float')
    
    def neural_network_model(data):
        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(data, 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):
        prediction = neural_network_model(x)
        cost = tf.reduce_mean(   tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,labels=y))
    
        optimizer = tf.train.AdamOptimizer().minimize(cost)
    
        hm_epochs = 10
    
        with tf.Session() as sess:
            sess.run(tf.initialize_all_variables())
    
            for epoch in range(hm_epochs):
                epoch_loss = 0
                for _ in range(int(mnist.train.num_examples/batch_size)):
                    epoch_x,epoch_y  = mnist.train.next_batch(batch_size)
                    _,epoch_c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
                    epoch_loss += epoch_c
                print('Epoch', epoch, 'completed out of ', hm_epochs, 'loss: ', epoch_loss)
            correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))
            accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
            print('Accuracy:', accuracy.eval({x:mnist.test.images, y: mnist.test.labels}))
    
    
    
    train_neural_network(x)
    

    【讨论】:

    • 添加一些关于您发布的解决方案的说明。
    猜你喜欢
    • 2018-06-21
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2018-07-06
    • 2017-02-11
    相关资源
    最近更新 更多