【问题标题】:How to output a prediction in Tensorflow?如何在 TensorFlow 中输出预测?
【发布时间】:2017-02-21 11:03:56
【问题描述】:

我正在尝试将 Tensorflow DNN 用于Kaggle Competion。数据大约有 100 列分类数据、29 列数值数据和 1 列用于输出。我所做的是我使用 Scikit 的 train test split 函数将它分成训练和测试 X 和 y,其中 X 是每行的列表,没有“id”或需要预测的值,y 是是需要预测的。然后我建立了模型,如下所示:

import tensorflow as tf
import numpy as np
import time
import pickle
with open('pickle.pickle', 'rb') as f:
    trainX, trainy, testX, testy = pickle.load(f)
trainX = np.array(trainX)
trainy = np.array(trainy)
trainy = trainy.reshape(trainy.shape[0], 1)
testX = np.array(testX)
testy = np.array(testy)
print (trainX.shape)
print (trainy.shape)
testX = testX.reshape(testX.shape[0], 130)
testy = testy.reshape(testy.shape[0], 1)
print (testX.shape)
print (testy.shape)
n_nodes_hl1 = 256
n_nodes_hl2 = 256
n_nodes_hl3 = 256

n_classes = 1

batch_size = 100


# Matrix = h X w
X = tf.placeholder('float', [None, len(trainX[0])])
y = tf.placeholder('float')

def model(data):

    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([trainX.shape[1], 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]))}

    # (input_data * weights) + biases

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

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

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.sigmoid(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']

    return output


def train(x):

    pred = model(x)
    #loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(pred, y))
    loss = tf.reduce_mean(tf.square(pred - y))
    optimizer = tf.train.AdamOptimizer(0.01).minimize(loss)

    epochs = 1

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        print ('Beginning Training \n')
        for e in range(epochs):
            timeS = time.time()
            epoch_loss = 0

            i = 0
            while i < len(trainX):

                start = i
                end = i + batch_size
                batch_x = np.array(trainX[start:end])
                batch_y = np.array(trainy[start:end])

                _, c = sess.run([optimizer, loss], feed_dict = {x: batch_x, y: batch_y})
                epoch_loss += c
                i += batch_size
            done = time.time() - timeS
            print ('Epoch', e + 1, 'completed out of', epochs, 'loss:', epoch_loss, "\nTime:", done, 'seconds\n')
        correct = tf.equal(tf.arg_max(pred, 1), tf.arg_max(y, 1))
        acc = tf.reduce_mean(tf.cast(correct, 'float'))
        print("Accuracy:", acc.eval({x:testX, y:testy}))


train(X)

1 epoch 的输出:

Epoch 1 completed out of 1 loss: 1498498282.5 
Time: 1.3765859603881836 seconds

Accuracy: 1.0

我确实意识到损失非常高,我使用 1 个 epoch 只是为了测试目的,是的,我知道我的代码非常混乱。但我想做的只是打印出一个预测。我该怎么做?我知道我需要提供 X 的功能列表,但我就是不明白该怎么做。我也不太明白为什么我的准确率是 1.0,所以如果您对此有任何建议,或者有任何更改我的代码的方法,我会更乐意听取任何想法。 提前致谢

【问题讨论】:

    标签: python-3.x neural-network tensorflow


    【解决方案1】:

    要获得预测,您只需评估 pred,这是定义模型输出的操作。

    怎么做?与pred.eval()。但是您需要输入来评估其预测,因此您必须向eval() 提供一个feed_dict 字典,其中包含您要处理的样本(或多个样本)。

    生成的代码如下所示:

    predictions = pred.eval(feed_dict = {x:testX})
    

    注意这与acc.eval({x:testX, y:testy}) 非常相似,因为想法是一样的。您有一个操作(在本例中为acc)需要评估一些输入,您可以通过调用acc.eval()sess.run(acc) 以及相应的feed_dict 和必要的输入来评估它。

    【讨论】:

      【解决方案2】:

      最简单的方法是在训练时(迭代之间)使用现有会话:

      print (sess.run(model, {x:X_example}))
      

      其中 X_example 是一些 numpy 示例张量。

      【讨论】:

      • 这里的型号是什么?
      • 看顶部。该模型是一个为张量流计算构建图的函数。 {x:X_example} 然后是 'feed_dict' 参数,它将真实数据放入所谓的 tensorflow“占位符”中。
      【解决方案3】:

      下面的行将为您提供每个班级的概率分数,例如您是 3 个班级,那么下面的行将为您提供一个 1x3 形状的数组 考虑到您想要预测单个数据点X_test,您可以执行以下操作:

      output = sess.run(pred, {x:X_test})
      

      上述变量output 中的最大数字将是您的预测,因此我们将修改上述语句:

      output = sess.run(tf.argmax(pred, 1), {x:X_test})
      print("your prediction for X_test is :", output[0])
      

      你可以做的其他事情是:

      output = sess.run(pred, {x:X_test})
      output = np.argmax(output)
      print("your prediction for X_test is :", output)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 2020-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多