如何解决具有所有按行排列的Tensorflow1 concat 2D张量
假设我们有两个形状为(n,k
和(n,k
)的2D张量。我们想用所有按行排列的方式组合这两个张量,以使所得的张量具有形状(n,n,2*k
)。
示例
A = [[a,b],[c,d]]; B = [[e,f],[g,h]]
结果张量应为:
[[[a,b,e,[a,g,h]],[[c,d,h]]]
假定输入张量A和B具有非静态形状,因此我们不能使用tf.shape()
索引值进行循环。
感谢您的帮助。非常感谢。
解决方法
尝试这种方式:
A = np.array([['a','b'],['c','d']])
B = np.array([['e','f'],['g','h']])
C = np.array([np.concatenate((a,b),axis=0) for a in A for b in B])
您可以像这样轻松地将其转换为张量流
data =tf.convert_to_tensor(C,dtype=tf.string)
输出:
<tf.Tensor: shape=(4,4),dtype=string,numpy=
array([[b'a',b'b',b'e',b'f'],[b'a',b'g',b'h'],[b'c',b'd',b'h']],dtype=object)>
不确定列表理解部分对于处理大数据是否最有效
,将tf.concat
与tf.repeat
和tf.tile
一起使用
import tensorflow as tf
import numpy as np
# Input
A = tf.convert_to_tensor(np.array([['a','d']]))
B = tf.convert_to_tensor(np.array([['e','h']]))
# Repeat,tile and concat
C = tf.concat([tf.repeat(A,repeats=tf.shape(A)[-1],axis=0),tf.tile(B,multiples=[tf.shape(A)[0],1])],axis=-1)
# Reshape to requested shape
C = tf.reshape(C,[tf.shape(A)[0],tf.shape(A)[0],-1])
print(C)
>>> <tf.Tensor: shape=(2,2,numpy=
>>> array([[[b'a',>>> [b'a',>>> [[b'c',>>> [b'c',b'h']]],dtype=object)>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。