在张量流中重新分配非变量张量



>我有一个要求,我想使用更新的x值作为RNN的输入。下面的代码片段可能会详细说明。

x = tf.placeholder("float", shape=[None,1])
RNNcell = tf.nn.rnn_cell.BasicRNNCell(....)
outputs, _ = tf.dynamic_rnn(RNNCell, tf.reshape(x, [1,-1,1]))
x = outputs[-1] * (tf.Varaibles(...) * tf.Constants(...)) 

@Vlad答案是正确的,但由于我是新成员不能投票。下面的代码片段是带有RNN单元的Vlads的更新版本。

x = tf.placeholder("float", shape=[None,1])
model = tf.nn.rnn_cell.BasicRNNCell(num_units=1, activation=None)
outputs, state = tf.nn.dynamic_rnn(model, tf.reshape(x, [-1,1, 1]), dtype=tf.float32)
# output1 = model.output 
# output1 = outputs[-1]
output1 = outputs[:,-1,:]
# output1 = outputs
some_value = tf.constant([9.0],     # <-- Some tensor the output will be multiplied by
                         dtype=tf.float32)
output1 *= some_value                # <-- The output had been multiplied by `some_value`
                                     #     (with broadcasting in case of
                                     #     more than one input samples)
with tf.control_dependencies([output1]): # <-- Not necessary, but explicit control
    output2, state2 = model(output1,state)  

这个例子或多或少是不言自明的。我们获取模型的输出,将其乘以某个张量(可以是标量,也可以是可以广播的秩> 0张量(,再次将其馈送到模型并得到结果:

import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, shape=(None, 2))
w = tf.Variable(tf.random_normal([2, 2]))
bias = tf.Variable(tf.zeros((2, )))
output1 = tf.matmul(x, w) + bias
some_value = tf.constant([3, 3],      # <-- Some tensor the output will be multiplied by
                         dtype=tf.float32)
output1 *= some_value*x  # <-- The output had been multiplied by `some_value`
                         #     (in this case with broadcasting in case of
                         #     more than one input sample)
with tf.control_dependencies([output1]):   # <-- Not necessary, but explicit control
    output2 = tf.matmul(output1, w) + bias #     dependencies is always good practice.
data = np.ones((3, 2)) # 3 two-dimensional samples
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(output2, feed_dict={x:data}))
    # [[3.0432963 3.6584744]
    #  [3.0432963 3.6584744]
    #  [3.0432963 3.6584744]]

最新更新