gpt4 book ai didi

python-2.7 - TensorFlow:如何确保张量在同一个图中

转载 作者:行者123 更新时间:2023-12-04 02:04:31 25 4
gpt4 key购买 nike

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

ValueError: Tensor("Placeholder:0", shape=(10, 5), dtype=float32) must be from the same graph as Tensor("windows/embedding/Cast:0", shape=(100232, 50), dtype=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 在同一个图中?

谢谢!!

最佳答案

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

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

关于python-2.7 - TensorFlow:如何确保张量在同一个图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40281170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com