尝试将 NN 定义为类时初始化 tf.variable 时出错



我正在尝试使用python类定义一个简单的张量流图,如下所示:

import numpy as np
import tensorflow as tf
class NNclass:
def __init__(self, state_d, action_d, state):
self.s_dim = state_d
self.a_dim = action_d
self.state = state
self.prediction
@property
def prediction(self):
a = tf.constant(5, dtype=tf.float32)
w1 = tf.Variable(np.random.normal(0, 1))
return tf.add(a, w1)
state = tf.placeholder(tf.float64, shape=[None, 1])
NN_instance = NNclass(1, 2, state)
ses = tf.Session()
ses.run(tf.global_variables_initializer())
nn_input = np.array([[0.5], [0.7]])
print(ses.run(NN_instance.prediction,  feed_dict={state: nn_input}))

当我运行此代码时,出现以下错误:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_1

在我看来,我有一个NNclass的实例,我浏览了 tf 图,因为def__init__超过了预测方法。 但我不明白为什么运行它会产生上述错误。 请提供任何帮助 谢谢

tf.global_variables_initializer()

应该在创建所有变量后调用。在您的示例中,prediction函数定义了w1变量,该变量直到ses.run()才初始化。

您可以在函数内部创建变量__init__如下所示:

class NNclass:
def __init__(self, state_d, action_d, state):
self.s_dim = state_d
self.a_dim = action_d
self.state = state
self.a = tf.constant(5, dtype=tf.float32)
self.w1 = tf.Variable(np.random.normal(0, 1))
@property
def prediction(self):
return tf.add(self.a, self.w1)

像您正在做的那样将函数的结果传递给sess.run()不是最佳做法,这会导致混淆。

配置网络的更好做法是创建一个build_graph()函数,其中定义了所有张量流操作。然后返回您需要计算的张量(更好的是,将它们存储在字典中或将它们保存为对象的属性)。

例:

def build_graph():
a = tf.constant(5, dtype=tf.float32)
w1 = tf.Variable(np.random.normal(0, 1))
a_plus_w = tf.add(a, w1)
state = tf.placeholder(tf.float64, shape=[None, 1])
return a_plus_w, state
a_plus_w, state = build_graph()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
nn_input = np.array([[0.5], [0.7]])
print(sess.run(a_plus_w,  feed_dict={state: nn_input}))

你犯的关键错误是你没有在tensorflow中分离开发的两个阶段。你有一个">构建图"阶段,你定义你想要执行的所有数学运算,然后你有一个"执行">阶段,你使用sess.run来要求tensorflow为你执行计算。当你调用sess.run你需要向张量流传递你想要计算的张量(已经在图中定义的 tf 对象)。你不应该向张量流传递一个要执行的函数。

最新更新