为什么这个张量流代码这么慢?

2024-04-20 09:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用TensorFlow训练一个深层神经网络多类分类器。网络从最后一层输出线性值,tf.nn.softmax_cross_entropy_with_logits成本函数将其作为输入。然而,我并不真正关心线性输出本身——我想知道当softmax函数应用于它时它是什么样子。在

以下是我的代码的相关部分:

def train_network(x, num_hidden_layers):
    prediction = neural_network_model(x, num_hidden_layers)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost)

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

        # train the network 
        ...

        # get the network output; x_test is my test data (len=663)
        output = sess.run(prediction,feed_dict={x: x_test})

        # get softmax values of output
        for i in range(len(x_test)):
            softm = sess.run(tf.nn.softmax(output[i]))
            pred_class = sess.run(tf.argmax(softm))
            print(pred_class)
            ...

现在,我计算softmax值的最后一个for循环非常慢。为什么会这样?我该怎么做?在


Tags: runtestoutputtfwithtrain线性nn