从拉平的上三角矩阵中,重构矩阵
重构矩阵
完整代码
ui = np.triu_indices(3)
di = np.tril_indices(3, -1)
mat = np.zeros((2, 3, 3))
x = np.random.randn(2, 6)
# 赋值上三角(包括对角线)
mat[:, ui[0], ui[1]] = x
# 赋值下三角(不包括对角线)
mat[:, di[0], di[1]] += mat.transpose((0, 2, 1))[:, di[0], di[1]]
1. 初始化矩阵,获得上/下三角下标
# 上三角矩阵的下标
ui = np.triu_indices(3)
# 下三角矩阵的下标,但偏移-1
di = np.tril_indices(3, -1)
# 初始化矩阵
mat = np.zeros((2, 3, 3))
## mat.shape == (2, 3, 3),2个3x3的矩阵
"""
ui:
(array([0, 0, 0, 1, 1, 2]), array([0, 1, 2, 1, 2, 2]))
di:
(array([1, 2, 2]), array([0, 0, 1]))
mat:
array([[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]])
"""
2. 初始化数据
# 拉平的上三角矩阵(随机初始化)
x = np.random.randn(2, 6)
## x.shape = (2, 6),其中2为样本数,6为上三角矩阵拉平后的维度
"""
array([[ 0.42794277, -0.26884712, -2.18755813, -1.48448215, -1.74511892,
-0.71074153],
[-0.11200397, 0.6248286 , -0.20929864, 0.57886718, 0.53131248,
-0.0503038 ]])
"""
3. 赋值上三角
# 赋值上三角(包括对角线)
mat[:, ui[0], ui[1]] = x
"""
mat:
array([[[ 0.42794277, -0.26884712, -2.18755813],
[ 0. , -1.48448215, -1.74511892],
[ 0. , 0. , -0.71074153]],
[[-0.11200397, 0.6248286 , -0.20929864],
[ 0. , 0.57886718, 0.53131248],
[ 0. , 0. , -0.0503038 ]]])
"""
4. 赋值下三角
利用 矩阵转置后,相加。
# 赋值下三角(不包括对角线)
mat[:, di[0], di[1]] += mat.transpose((0, 2, 1))[:, di[0], di[1]]
"""
mat:
array([[[ 0.42794277, -0.26884712, -2.18755813],
[-0.26884712, -1.48448215, -1.74511892],
[-2.18755813, -1.74511892, -0.71074153]],
[[-0.11200397, 0.6248286 , -0.20929864],
[ 0.6248286 , 0.57886718, 0.53131248],
[-0.20929864, 0.53131248, -0.0503038 ]]])
"""
补充
torch.triu_indices
获得row * col
矩阵的上三角下标,offset
为与主对角线的偏移。
torch.triu_indices(
row, # 二维矩阵的行数
col, # 二位矩阵的列数
offset # 与主对角线的偏移
)
a = torch.triu_indices(3, 3)
a
"""
tensor([[0, 0, 0, 1, 1, 2],
[0, 1, 2, 1, 2, 2]])
a.shape = (2, 3*4/2) = (2, 6)
"""
torch.tril_indices
同上,但获取的是矩阵的下三角下标。