貌似在当前 tensorflow 版本中没有定义外积操作

dim = 6

template1 = np.zeros([dim,dim*dim])
for i in range(dim):
    for j in range(dim):
        template1[i,dim*i+j] = 1
log_info(template1)
''' 
dim = 4
[[1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1.]] 

'''
template2 = np.zeros([dim,dim*dim])
for i in range(dim):
    for j in range(dim):
        template2[i,dim*j+i] = 1
log_info(template2)
'''
dim = 4
[[1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0.]
 [0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1.]] 
'''

def outer_product(a, b):
    tml1 = tf.convert_to_tensor(template1, dtype=float)
    tml2 = tf.convert_to_tensor(template2, dtype=float)
    return tf.matmul(a,tml1)*tf.matmul(b,tml2)

给定两个同维向量 a b

a = np.array([[i+1 for i in range(dim)]])
b = a.copy()
log_info(a)
log_info(b)
[[1 2 3 4 5 6]] 
[[1 2 3 4 5 6]] 

求它们的外积

a = tf.convert_to_tensor(a, dtype=float)
b = tf.convert_to_tensor(b, dtype=float)
c = outer_product(a, b)  
c = tf.reshape(c,[-1,dim,dim])
print(c.shape)
with tf.Session() as sess:
    print(sess.run(c))
(1, 6, 6)
[[[ 1.  2.  3.  4.  5.  6.]
  [ 2.  4.  6.  8. 10. 12.]
  [ 3.  6.  9. 12. 15. 18.]
  [ 4.  8. 12. 16. 20. 24.]
  [ 5. 10. 15. 20. 25. 30.]
  [ 6. 12. 18. 24. 30. 36.]]]
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐