将对角矩阵提高到负功率1/2

时间:2015-03-03 04:40:37

标签: python numpy matrix

我正在尝试计算具有以下等式的矩阵。

S = (D^−1/2) * W * (D^−1/2)

其中 D 是此形式的对角矩阵:

array([[ 0.59484625,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.58563893,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.58280472,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.58216725]])

W

array([[ 0.        ,  0.92311635,  0.94700586,  0.95599748],
       [ 0.92311635,  0.        ,  0.997553  ,  0.99501248],
       [ 0.94700586,  0.997553  ,  0.        ,  0.9995501 ],
       [ 0.95599748,  0.99501248,  0.9995501 ,  0.        ]])

我尝试使用D^-1/2函数numpylinalg.matrix_power(D,-1/2)以及numpy.power(D,-1/2)函数引发matrix_powerTypeError: exponent must be an integer来计算numpy.power函数引发RuntimeWarning: divide by zero encountered in power

如何计算对角矩阵的负功率-1/2。请帮忙。

3 个答案:

答案 0 :(得分:4)

如果你可以更新D(就像你自己的答案一样),那么只需更新对角线索引处的项目,然后拨打np.dot

>>> D[np.diag_indices(4)] = 1/ (D.diagonal()**0.5)
>>> np.dot(D, W).dot(D)
array([[ 0.        ,  0.32158153,  0.32830723,  0.33106193],
       [ 0.32158153,  0.        ,  0.34047794,  0.33923936],
       [ 0.32830723,  0.34047794,  0.        ,  0.33913717],
       [ 0.33106193,  0.33923936,  0.33913717,  0.        ]])

或创建一个新的零数组,然后使用1/ (D.diagonal()**0.5)填充其对角元素:

>>> arr = np.zeros(D.shape)
>>> np.fill_diagonal(arr, 1/ (D.diagonal()**0.5))
>>> np.dot(arr, W).dot(arr)
array([[ 0.        ,  0.32158153,  0.32830723,  0.33106193],
       [ 0.32158153,  0.        ,  0.34047794,  0.33923936],
       [ 0.32830723,  0.34047794,  0.        ,  0.33913717],
       [ 0.33106193,  0.33923936,  0.33913717,  0.        ]])

答案 1 :(得分:0)

我通过计算thro'数学术语得到了答案,但很想看到任何直接的单线:)

def compute_diagonal_to_negative_power():
    for i in range(4):
        for j in range(4):
            if i == j:
                element = D[i][j]
                numerator = 1
                denominator = math.sqrt(element)
                D[i][j] = numerator / denominator
    return D


diagonal_matrix = compute_diagonal_to_negative_power()

S = np.dot(diagonal_matrix, W).dot(diagonal_matrix)
print(S)

"""
[[ 0.          0.32158153  0.32830723  0.33106193]
 [ 0.32158153  0.          0.34047794  0.33923936]
 [ 0.32830723  0.34047794  0.          0.33913718]
 [ 0.33106193  0.33923936  0.33913718  0.        ]]
"""

来源:https://math.stackexchange.com/questions/340321/raising-a-square-matrix-to-a-negative-half-power

答案 2 :(得分:0)

您可以执行以下操作:

sudo -H -u user1 bash <<"EOF"
presentdir="$(pwd)"
echo "$presentdir"
EOF

然后您将避免得到警告: RuntimeWarning:除以零的幂次

numpy会将矩阵元素上的每个值除以它自己的平方根(不为零),因此基本上您将不再尝试除以零。