Sun Hao Lun
Sun Hao Lun

Reputation: 313

Tensorflow: how to concat tensor with specific index

I have tensors like these:

tensor_a = [[[[255,255,255]]], [[[100,100,100]]]]
tensor_b = [[[[0.1,0.2]]], [[[0.3,0.4]]]]
tensor_c = [[[[1]]], [[[2]]]]

Today I try to concat these tensors above to tensor_d like:

tensor_d = [[[[255,255,255,0.1,1]]], [[[100,100,100, 0.3, 2]]]]

But I have no idea how to concat them.

I had tried to using for loop to append tensor to list

but that was too slow(under the shape of tensor_a:(10,64,64,3))

Upvotes: 0

Views: 922

Answers (2)

Sihyeon Kim
Sihyeon Kim

Reputation: 161

You can use tensor manipulation such as tf.split and tf.concat.

import tensorflow as tf

# tensors
tensor_a = [[[[255, 255, 255]]], [[[100, 100, 100]]]]
tensor_b = [[[[0.1, 0.2]]], [[[0.3, 0.4]]]]
tensor_c = [[[[1]]], [[[2]]]]

# casting becuase date type should match in tf.concat
tensor_a = tf.cast(tensor_a, dtype=tf.float32)
tensor_c = tf.cast(tensor_c, dtype=tf.float32)

# split elements into one and the other at the last axis
b, _ = tf.split(value=tensor_b, num_or_size_splits=[1, -1], axis=-1)
c, _ = tf.split(value=tensor_c, num_or_size_splits=[1, -1], axis=-1)

# concatenate tensors at the last axis
tensors = tf.concat(values=[tensor_a, b, c], axis=-1)

sess = tf.Session()
result = sess.run(tensors)

print(result)
[[[[2.55e+02 2.55e+02 2.55e+02 1.00e-01 1.00e+00]]]


 [[[1.00e+02 1.00e+02 1.00e+02 3.00e-01 2.00e+00]]]]

Upvotes: 1

kederrac
kederrac

Reputation: 17322

You can try

tensor_a = [[[[255,255,255]]], [[[100,100,100]]]]
tensor_b = [[[[0.1,0.2]]], [[[0.3,0.4]]]] 
tensor_c = [[[[1]]], [[[2]]]]

tensor_d = [[[a[0][0] + [b[0][0][0]] + [c[0][0][0]]]] for a, b, c in zip( tensor_a, tensor_b, tensor_c)]
print(tensor_d) 

# [[[[255, 255, 255, 0.1, 1]]], [[[100, 100, 100, 0.3, 2]]]]

Upvotes: 1

Related Questions