Vinod prime
Vinod prime

Reputation: 81

Reassign non-variable tensor in tensorflow

I have a requirement, that I want to use the updated value of x as an input to RNN. The below code snippet might illustrate you in detail.

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(...)) 

Upvotes: 1

Views: 92

Answers (2)

Vinod prime
Vinod prime

Reputation: 81

@Vlad answer is correct but since am new member cannot vote. The below code snippet is updated version of Vlads one with RNN cell.

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)  

Upvotes: 1

Vlad
Vlad

Reputation: 8585

The example is more or less self-explanatory. We take the output of the model, multiply it by some tensor (could be scalar, or tensor with rank > 0 that could be broadcasted), feed it again to the model and get the result:

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]]

Upvotes: 0

Related Questions