本文介绍了尝试评估张量流中的新数据实例时出现 ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 tensorflow 中的前馈 DNN 图来预测新数据实例的分类.

I am trying to predict the classification of a new instance of data using the feed forward DNN graph in tensorflow.

代码是:

import tensorflow as tf
import pandas as pd

dataframe = pd.read_csv("jfkspxstrain.csv") # Let's have Pandas load our dataset as a dataframe
dataframe = dataframe.drop(["Field6", "Field9", "rowid"], axis=1) # Remove columns we don't care about
dataframe.loc[:, ("y2")] = dataframe["y1"] == 0           # y2 is the negation of y1
dataframe.loc[:, ("y2")] = dataframe["y2"].astype(int)    # Turn TRUE/FALSE values into 1/0
trainX = dataframe.loc[:, ['Field2', 'Field3', 'Field4', 'Field5', 'Field7', 'Field8', 'Field10']].as_matrix()
trainY = dataframe.loc[:, ["y1", 'y2']].as_matrix()

dataframe = pd.read_csv("jfkspxstest.csv") # Let's have Pandas load our dataset as a dataframe
dataframe = dataframe.drop(["Field6", "Field9", "rowid"], axis=1) # Remove columns we don't care about
dataframe.loc[:, ("y2")] = dataframe["y1"] == 0           # y2 is the negation of y1
dataframe.loc[:, ("y2")] = dataframe["y2"].astype(int)    # Turn TRUE/FALSE values into 1/0
testX = dataframe.loc[:, ['Field2', 'Field3', 'Field4', 'Field5', 'Field7', 'Field8', 'Field10']].as_matrix()
testY = dataframe.loc[:, ["y1", 'y2']].as_matrix()

n_nodes_hl1 = 10
n_nodes_hl2 = 10
n_nodes_hl3 = 10

n_classes = 2
batch_size = 1

x = tf.placeholder('float',[None, 7])
y = tf.placeholder('float')

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([7, 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_hl1, 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(prediction,y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 5

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

        for epoch in range(hm_epochs):
            epoch_loss = .1
            for _ in range(399):
                _, c = sess.run([optimizer, cost], feed_dict = {x: trainX, y: trainY})
                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))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:',accuracy.eval({x: testX, y: testY}))
        classification = y.eval(feed_dict={x: [51.0,10.0,71.0,65.0,5.0,70.0,30.06]})
        print (classification)
train_neural_network(x)

错误是:

ValueError: Cannot feed value of shape (7,) for Tensor 'Placeholder:0', which has shape '(?, 7)'

在这条线上

classification = y.eval(feed_dict={x: [51.0,10.0,71.0,65.0,5.0,70.0,30.06]})

我不知道从哪里开始,因为我不想改变占位符中的值,因为我认为它们是需要的地方.任何帮助表示赞赏.谢谢!

I'm not sure where to begin as I don't want to change around the values in my placeholders as I think they are where they need to be. Any help is appreciated. Thanks!

推荐答案

在输入周围添加另一个 [] 应该可以解决您的问题.[51.0,10.0,71.0,65.0,5.0,70.0,30.06] 是形状 (7,) 但 [[[51.0,10.0,71.0,65.0,5.0,70.0,30.06]] 是 (1,7)

Adding another [] around the input should resolve your problem. [51.0,10.0,71.0,65.0,5.0,70.0,30.06] is shape (7,) but [[51.0,10.0,71.0,65.0,5.0,70.0,30.06]] is (1,7)

classification = y.eval(feed_dict={x: [[51.0,10.0,71.0,65.0,5.0,70.0,30.06]]})

这篇关于尝试评估张量流中的新数据实例时出现 ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:14