Python – Error in Tensorflow equivalent to Subtensor

Error in Tensorflow equivalent to Subtensor… here is a solution to the problem.

Error in Tensorflow equivalent to Subtensor

I tried to use the following code to equate to tensors in tensorflow:

import tensorflow as tf
import numpy as np
a = tf.placeholder(tf.float32, shape=[2,2])
b = tf. Variable(tf.zeros(shape = [1,1]))

sess = tf. Session()
b[0,0]=a[0,0]
sess.run(tf.initialize_all_variables())

However, the error message “Project allocation is not supported for the ‘RefVariable’ object” appears. How do I change it?

Solution

You must create a tensor that performs the distribution and runs it. You can assign slices:

assg = b[0,0].assign(a[0,0])
feed_dict = {a: np.array([[3,4],[5,6]])}
sess.run(assg, feed_dict=feed_dict)
print(sess.run(b)) # [[3.]]

Since you actually want to assign a new value to the entire b, you can also just use tf.assign, but you have to make sure the shapes match, because a[0,0] is a number and b is a matrix of size 1×1.

assg = tf.assign(b, tf.reshape(a[0,0],shape=[1,1]))
feed_dict = {a: np.array([[3,4],[5,6]])}
sess.run(assg, feed_dict=feed_dict)
print(sess.run(b)) # [[3.]]

Related Problems and Solutions