首页 文章

TensorFlow:如何确保张量在同一图表中

提问于
浏览
9

我正在尝试在python中开始使用TensorFlow,构建一个简单的前馈NN . 我有一个类,它包含网络权重(在训练期间更新的变量,并且应该在运行时保持不变)和另一个训练网络的脚本,它获取训练数据,将它们分成批次并分批训练网络 . 当我尝试训练网络时,我收到一个错误,表明数据张量与NN张量不在同一个图中:

ValueError:Tensor(“占位符:0”,形状=(10,5),dtype = float32)必须与Tensor相同的图形(“windows / embedding / Cast:0”,shape =(100232,50), D型= FLOAT32) .

培训脚本中的相关部分是:

def placeholder_inputs(batch_size, ner):
  windows_placeholder = tf.placeholder(tf.float32, shape=(batch_size, ner.windowsize))
  labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
  return windows_placeholder, labels_placeholder

with tf.Session() as sess:
  windows_placeholder, labels_placeholder = placeholder_inputs(batch_size, ner)
  logits = ner.inference(windows_placeholder)

而网络类中的相关内容是:

class WindowNER(object):
def __init__(self, wv, windowsize=3, dims=[None, 100,5], reg=0.01):
    self.reg=reg
    self.windowsize=windowsize
    self.vocab_size = wv.shape[0]
    self.embedding_dim = wv.shape[1]
    with tf.name_scope("embedding"):
        self.L = tf.cast(tf.Variable(wv, trainable=True, name="L"), tf.float32)
    with tf.name_scope('hidden1'):
        self.W = tf.Variable(tf.truncated_normal([windowsize * self.embedding_dim, dims[1]],
            stddev=1.0 / math.sqrt(float(windowsize*self.embedding_dim))),
        name='weights')
        self.b1 = tf.Variable(tf.zeros([dims[1]]), name='biases')
    with tf.name_scope('output'):
        self.U = tf.Variable(tf.truncated_normal([dims[1], dims[2]], stddev = 1.0 / math.sqrt(float(dims[1]))), name='weights')
        self.b2 = tf.Variable(tf.zeros(dims[2], name='biases'))


def inference(self, windows):
    with tf.name_scope("embedding"):
        embedded_words = tf.reshape(tf.nn.embedding_lookup(self.L, windows), [windows.get_shape()[0], self.windowsize * self.embedding_dim])
    with tf.name_scope("hidden1"):
        h = tf.nn.tanh(tf.matmul(embedded_words, self.W) + self.b1)
    with tf.name_scope('output'):
        t = tf.matmul(h, self.U) + self.b2

为什么首先有两个图,我如何确保数据占位符张量与NN在同一个图中?

谢谢!!

2 回答

  • 5

    您应该能够通过执行以下操作在同一图表下创建所有张量:

    g = tf.Graph()
    with g.as_default():
      windows_placeholder, labels_placeholder = placeholder_inputs(batch_size, ner)
      logits = ner.inference(windows_placeholder)
    
    with tf.Session(graph=g) as sess:
      # Run a session etc
    

    你可以在这里阅读更多关于TF的图表:https://www.tensorflow.org/versions/r0.8/api_docs/python/framework.html#Graph

  • 4

    有时当你得到这样的错误时,错误(通常可以使用来自不同图形的错误变量)可能更早发生,并传播到最终引发错误的操作 . 因此,您可能只调查该行,并得出结论,张量应该来自同一个图,而错误实际上位于其他地方 .

    最简单的检查方法是打印出图中每个变量/ op使用的图形 . 你可以这样做:

    print(variable_name.graph)
    

相关问题