Home > Back-end >  How to insert certain values to a tensor in tensorflow?
How to insert certain values to a tensor in tensorflow?

Time:12-24

I want to convert

from = [
    [1],[2],[3],[4],
]

shape (4, 1)

this tensor

to = [
    [1,1],[2,2],[3,3],[4,4],
]

shape (4, 2)

this tensor.

CodePudding user response:

Use tf.tile, tf.repeat, tf.concat or tf.stack:

import tensorflow as tf

from_tensor = tf.constant([[1],[2],[3],[4]])
to_tensor_with_tile = tf.tile(from_tensor, [1, 2])
to_tensor_with_repeat = tf.repeat(from_tensor, repeats=2, axis=1)
to_tensor_with_concat = tf.concat([from_tensor, from_tensor], axis=1)
to_tensor_with_stack = tf.squeeze(tf.stack([from_tensor, from_tensor], axis=-1), axis=1)

print(to_tensor_with_tile)
print(to_tensor_with_repeat)
print(to_tensor_with_concat)
print(to_tensor_with_stack)
tf.Tensor(
[[1 1]
 [2 2]
 [3 3]
 [4 4]], shape=(4, 2), dtype=int32)
tf.Tensor(
[[1 1]
 [2 2]
 [3 3]
 [4 4]], shape=(4, 2), dtype=int32)
tf.Tensor(
[[1 1]
 [2 2]
 [3 3]
 [4 4]], shape=(4, 2), dtype=int32)
tf.Tensor(
[[1 1]
 [2 2]
 [3 3]
 [4 4]], shape=(4, 2), dtype=int32)
  • Related