Tensorflow:如何用特定索引连接张量

时间:2019-08-11 16:34:28

标签: python tensorflow deep-learning

我有这样的张量:

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

今天,我尝试将上面的这些张量连接到tensor_d上,

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

但是我不知道如何吸引他们。

我曾尝试使用for循环将张量附加到列表中

但是那太慢了(以tensor_a:(10,64,64,3)的形式)

2 个答案:

答案 0 :(得分:1)

您可以尝试

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]]]]

答案 1 :(得分:1)

您可以使用张量操纵,例如tf.splittf.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]]]]