I have a tensor which is simply a vector, vector = [0.5 0.4]
and tf.shape indicates that it has shape=(1,), I would like to replicate the vector m times and have the shape of [m, 2], so for m = 2, matrix = [[0.5 0.4], [0.5 0.4]]
. How do I achieve that using tf.tile?
标签:
tensorflow
相关问题
- batch_dot with variable batch size in Keras
- How to use Reshape keras layer with two None dimen
- CV2 Image Error: error: (-215:Assertion failed) !s
- Why keras use “call” instead of __call__?
- How to conditionally scale values in Keras Lambda
相关文章
- tensorflow 神经网络 训练集准确度远高于验证集和测试集准确度?
- Tensorflow: device CUDA:0 not supported by XLA ser
- Numpy array to TFrecord
- conditional graph in tensorflow and for loop that
- How to downgrade to cuda 10.0 in arch linux?
- Apply TensorFlow Transform to transform/scale feat
- How to force tensorflow tensors to be symmetric?
- keras model subclassing examples
replicating / duplicating a tensor (be it a 1D vector, 2D matrix, or any dimension) can be done by creating a list of copies of this tensor (with pure python), and then using tf.stack - having both steps in one (short) line. Here is an example of duplicating a 2D Tensor:
"[a]*4" creates a list containing four copies of the same tensor (this is pure python). tf.stack then stack them one after the other, on the first axis (axis=0)
In graph mode:
Tensorflow 2.0 solution: Refer to this link to read more about tf.tile
Take the following,
vec
is a vector,multiply
is your m, the number of times to repeat the vector.tf.tile
is performed on the vector and then usingtf.reshape
it is reshaped into the desired structure.This results in:
The same can be achieved by multiplying a
ones matrix
withvec
and letbroadcasting
do the trick:An answer without reshaping:
I assume that the main use case of such replication is to match the dimensionality of two tensors (that you want to multiply?).
In that case, there is a much simpler solution. Let the
tensorflow
do the work of dimensionality matching for you:As you can see it can work for much more complex situations: when you need to replicate on both first and last dimensions, when you are working with more complex shapes, etc. All you need to do is match the indices in the string description (above we match the dimension of
a
, labeledj
with the second dimension ofb
(ijk
).Another example use case: I have a state per neuron, and since we simulate in batches, this state has dimensionality
(n_batch, n_neuron)
. I need to use this state to modulate connections between neurons (weights of synapses), which in my case had additional dimension so they have the dimensionality(n_neuron, n_neuron, n_X)
.Instead of making a mess with tiling, reshaping, etc. I can just write it in a single line like so: