假设我有一个秩二张量,[[a,b],[c,d]](通常是一个m-by-n矩阵).
我想用一个2-2的恒等矩阵(外积)来扩展每个元素,并得到
[[a, 0, b, 0],[0,a,0,b],[c,0,d,0],[0,c,0,d]]. 在tensorflow中实现它的最有效方法是什么?
这个操作在框架中出现了很多。
发布于 2018-10-19 10:13:15
我想用两步的方法来做。如果我有一个m-by-n矩阵和2-2恒等矩阵。首先,我将把矩阵放大(重复)到"2m-2n矩阵“。
然后乘以扩大的单位矩阵(2m-2n矩阵)。如下所示。
import tensorflow as tf
#Process 1 repeat the tensor in 2D.
#e.g. [1,2,3,4] --> [[1,1,2,2],[1,1,2,2],[3,3,4,4],[3,3,4,4]]
# assuming m x n idenity matrix e.g. [1,2,3],[4,5,6]] , m=2,n=3
id_matrix_size=2 # size of identity matrix (e.g. 2x2 3x3 ...)
m=2
n=3
mytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)
# similar to np.repeat in x-dimension.
flatten_mytensor=tf.reshape(mytensor,[-1,1])
a=tf.tile(flatten_mytensor, [1, id_matrix_size])
b=tf.reshape( a, [m,-1])
# tile in y-dimension
c=tf.tile(b,[1,id_matrix_size])
d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])
#Process 2 tile identity matrix in 2D.
identity_matrix=tf.eye(id_matrix_size) # identity matrix
identity_matrix_2D= tf.tile(identity_matrix,[m,n])
#Process 3 elementwise multiply
output = tf.multiply(d,identity_matrix_2D )
with tf.Session() as sess:
print(sess.run(output) )
#output :
#[[1. 0. 2. 0. 3. 0.]
# [0. 1. 0. 2. 0. 3.]
# [4. 0. 5. 0. 6. 0.]
# [0. 4. 0. 5. 0. 6.]]而且,如果需要大量的工具,那么def就更方便了。
def Expand_tensor(mytensor,id_matrix_size):
m=mytensor.shape[0]
n=mytensor.shape[1]
# similar to np.repeat in x-dimension.
flatten_mytensor=tf.reshape(mytensor,[-1,1])
a=tf.tile(flatten_mytensor, [1, id_matrix_size])
b=tf.reshape( a, [m,-1])
# tile in y-dimension
c=tf.tile(b,[1,id_matrix_size])
d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])
# tile identity matrix in 2D.
identity_matrix=tf.eye(id_matrix_size) # identity matrix
identity_matrix_2D= tf.tile(identity_matrix,[m,n])
#elementwise multiply
output = tf.multiply(d,identity_matrix_2D )
return output
mytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)
with tf.Session() as sess:
print(sess.run(Expand_tensor(mytensor,2)) )https://stackoverflow.com/questions/52887179
复制相似问题