测试张量,模态展开和折叠函数
tensor = np.array([[[0, 3, 6, 9],[1, 4, 7, 10],[2, 5, 8, 11]],[[12, 15, 18, 21],[13, 16, 19, 22],[14, 17, 20, 23]]])def mode_k_folding(mat, k, dim):dim0 = list(dim[:k-1]) + list(dim[k:])dim0.append(dim[k-1])mat = mat.transpose() ten = np.reshape(mat, dim0, order='F')ten = np.moveaxis(ten, -1, k-1)return tendef mode_k_unfolding(tensor, mode):"""tensor: 输入的张量mode: 展开的模态 1,2,3测试完成!"""mode -= 1return np.reshape(np.moveaxis(tensor, mode, 0), (tensor.shape[mode], -1), order = 'F')
测试结果
a = TQB.get_tensor()
print(a)
b = TQB.mode_k_unfolding(a, 3)
print(b)
c = TQB.mode_k_folding(b, 3, a.shape)
print(c)
[[[ 1 13][ 4 16][ 7 19][10 22]][[ 2 14][ 5 17][ 8 20][11 23]][[ 3 15][ 6 18][ 9 21][12 24]]]
[[ 1 2 3 4 5 6 7 8 9 10 11 12][13 14 15 16 17 18 19 20 21 22 23 24]]
[[[ 1 13][ 4 16][ 7 19][10 22]][[ 2 14][ 5 17][ 8 20][11 23]][[ 3 15][ 6 18][ 9 21][12 24]]]