Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the shape of a variable in TensorFlow?

Tags:

TensorFlow tutorial says that at creation time we need to specify the shape of tensors. That shape automatically becomes the shape of the tensor. It also says that TensorFlow provides advanced mechanisms to reshape variables. How can I do that? Any code example?

like image 884
Jadiel de Armas Avatar asked Nov 11 '15 16:11

Jadiel de Armas


People also ask

How do you modify a tensor value?

we can modify a tensor by using the assignment operator. Assigning a new value in the tensor will modify the tensor with the new value.


2 Answers

The tf.Variable class is the recommended way to create variables, but it restricts your ability to change the shape of the variable once it has been created.

If you need to change the shape of a variable, you can do the following (e.g. for a 32-bit floating point tensor):

var = tf.Variable(tf.placeholder(tf.float32)) # ... new_value = ...  # Tensor or numpy array. change_shape_op = tf.assign(var, new_value, validate_shape=False) # ... sess.run(change_shape_op)  # Changes the shape of `var` to new_value's shape. 

Note that this feature is not in the documented public API, so it is subject to change. If you do find yourself needing to use this feature, let us know, and we can investigate a way to support it moving forward.

like image 142
mrry Avatar answered Oct 12 '22 23:10

mrry


Take a look at shapes-and-shaping from TensorFlow documentation. It describes different shape transformations available.

The most common function is probably tf.reshape, which is similar to its numpy equivalent. It allows you to specify any shape that you want as long as the number of elements stays the same. There are some examples available in the documentation.

like image 23
Rafał Józefowicz Avatar answered Oct 12 '22 21:10

Rafał Józefowicz