Tensorflow占位符不是此图的元素

时间:2018-04-15 00:48:09

标签: python tensorflow neural-network

我试图通过编码多层感知器分类器来了解张量流的工作原理。我在这种情况下使用MNIST数据集。我想创建一个神经网络类,它有自己的张量流图,并有一个训练它的函数。我知道有更简单的方法可以做到这一点,但我想学习,我想了解这个错误。

这是我的代码:

class neural_network_tensor:
def __init__(self, hidden_layers, learning_rate, input_size, output_size):
    self.graph=tf.Graph()
    with self.graph.as_default():
        layer_dim=[input_size]+hidden_layers+[output_size]
        x = tf.placeholder(tf.float32, [None, input_size])
        y_true = tf.placeholder(tf.float32, [None, output_size])
        #layers
        logits=[x]
        weights=[]
        biases=[]
        #hidden layers
        for i in range(len(layer_dim)-1):
            weights.append(tf.Variable(tf.zeros([layer_dim[i], layer_dim[i+1]])))
            biases.append(tf.Variable(tf.zeros([layer_dim[i+1]])))
            logits.append(tf.nn.relu(tf.matmul(logits[i],weights[i])+ biases[i]))
        self.y_pred = tf.nn.softmax(logits[-1])
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits[-1],
                                                                labels=y_true)
        self.cost = tf.reduce_mean(cross_entropy)
        self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(self.cost)
        correct_prediction = tf.equal(self.y_pred, y_true)
        self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print(x)

def train(self, num_iterations, batch_size, data, session):
    for i in range(num_iterations):
        # Get a batch of training examples.
        # x_batch now holds a batch of images and
        # y_true_batch are the true labels for those images.
        x_batch, y_true_batch = data.train.next_batch(batch_size)

        # Put the batch into a dict with the proper names
        # for placeholder variables in the TensorFlow graph.
        # Note that the placeholder for y_true_cls is not set
        # because it is not used during training.
        feed_dict_train = {x: x_batch,
                           y_true: y_true_batch}

        # Run the optimizer using this batch of training data.
        # TensorFlow assigns the variables in feed_dict_train
        # to the placeholder variables and then runs the optimizer.
        session.run(self.optimizer, feed_dict=feed_dict_train)

def print_accuracy(self, data, session):
    feed_dict_test = {x: data.test.images,
                  y_true: data.test.labels,
                  y_true_cls: data.test.cls}
    # Use TensorFlow to compute the accuracy.
    acc = session.run(self.accuracy, feed_dict=feed_dict_test)

    # Print the accuracy.
    print("Accuracy on test-set: {0:.1%}".format(acc))


net=neural_network_tensor([1], 0.1, img_size_flat, 10)
with net.graph.as_default():
    sessi=tf.Session()
    net.train(5, 100, data, sessi)

这是我得到的错误:

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(?, 784), dtype=float32) is not an element of this graph.

"占位符:0"张量是网的x。我很感激有关如何调试它的任何帮助。

1 个答案:

答案 0 :(得分:1)

我相信你这里有一个普通的旧Python范围问题。您可以在x方法中定义__init__,但无法将值x传递给任何人。

当你到达

    feed_dict_train = {x: x_batch,
                       y_true: y_true_batch}
train方法中的

x未定义,或者可能是全局的。您必须将x传递给调用者并将其移交给其他方法,或者您可以将其分配给self.x = x这样的实例并以这种方式使用它,或者第三种方法是将其赋予它在汇编饲料字典之前,使用名称将其从名称中删除。