是否可以在方法内部将tensorflow变量设置为输入数据的第一个值?
假设我们有输入数据,例如x [0],x [1],... x [N-1]。 我想让一个tensorflow变量在Python方法中存储第一个“ x [0]”值。以下是简化的代码:
static void irc_on_join ( irc_session_t* session, event_type event, const char* origin, const char** params, unsigned int count );
是否有可能这样做?
答案 0 :(得分:1)
您可以尝试一下。这里的placeholder[:1]
是切片语法,用于获取第一个值为1
u = u.assign(placeholder[:1])
是第一个元素的分配。
import tensorflow as tf
placeholder = tf.placeholder( tf.int32, shape=(4,))
def Graph(placeholder):
# I want to store the first value of placeholder in "u"
with tf.variable_scope("reuse", reuse=tf.AUTO_REUSE):
u = tf.get_variable('x',[1],dtype=tf.int32, trainable=False)
u = u.assign(placeholder[:1])
place_print = tf.Print(placeholder[:1],[placeholder[:1]])
u_print = tf.Print(u,[u])
# Some calculation including 'u'
y = 7 * place_print - u_print
return y
with tf.Session() as sess:
with tf.variable_scope("reuse", reuse=tf.AUTO_REUSE):
u = tf.get_variable("x", [1], dtype=tf.int32)
f = Graph(placeholder)
sess.run( tf.global_variables_initializer() )
print(sess.run( [f,u],feed_dict={placeholder: [1, 2, 3, 4]}))
输出为
[array([6]), array([0])]