numpy array多维张量

这里举三维为例子:

一直两个数据集 X=[X_1,X_2,... X_n], Y=[Y_1,Y_2,... Y_m] ; X_i = [X_i_1,X_i_2,...,X_i_l], Y_i = [Y_i_1,Y_i_2,...,Y_i_l]

X=[ [X_1_1,X_1_2,...,X_1_l],

  [X_2_1,X_2_2,...,X_2_l],

  ...

  [X_n_1,X_n_2,...,X_n_l]]

 

X_1 = np.random.randint(1,10,(8,4))
X_2 = np.random.randint(1,10,(6,4))
n_X_1, n_X_2 = len(X_1), len(X_2)

>>> X_1 # 8*4
array([[7, 2, 9, 3],
       [9, 4, 8, 6],
       [7, 7, 2, 4],
       [8, 5, 9, 8],
       [8, 2, 5, 9],
       [6, 3, 7, 7],
       [6, 6, 5, 4],
       [5, 6, 8, 6]])
>>> X_2 # 6*4
array([[8, 8, 4, 2],
       [2, 4, 8, 3],
       [1, 2, 6, 9],
       [5, 4, 4, 7],
       [7, 9, 4, 8],
       [8, 9, 7, 3]])

 

 

 

>>> def get_D(X_1, X_2): # n*l, m*l
...     n_X_1, n_X_2 = len(X_1), len(X_2)  # n, m
...     temp_X_1 = np.array([X_1] * n_X_2) # m*n*l
...     temp_X_2 = np.array([X_2] * n_X_1) # n*m*l
...     temp_X_1 = np.transpose(temp_X_1, (1, 0, 2)) # n*m*l
...     temp = (temp_X_1 - temp_X_2)**2 # n*m*l
...     D = np.sum(temp, axis=2) # n*m
...     return D
...
>>> d = get_D(X_1,X_2)
>>> d
array([[ 63,  30,  81,  49,  99,  54],
       [ 49,  58,  81,  33,  49,  36],
       [ 10,  71, 102,  26,  24,  31],
       [ 70,  63,  68,  36,  42,  45],
       [ 86,  85,  50,  18,  52,  89],
       [ 63,  34,  31,  11,  47,  56],
       [ 13,  30,  67,  15,  27,  18],
       [ 45,  22,  45,  21,  33,  28]], dtype=int32)
>>> d.shape
(8, 6)
>>> sum((X_1[0] - X_2[0])**2)
63
>>> sum((X_1[0] - X_2[1])**2)
30
>>> sum((X_1[0] - X_2[2])**2)
81
>>> sum((X_1[2] - X_2[1])**2)
71
>>> sum((X_1[3] - X_2[2])**2)
68

与我们想要的一致

 

posted @ 2018-04-15 22:33  chen狗蛋儿  阅读(291)  评论(0编辑  收藏  举报