如何在python中生成随机稀疏Hermitian矩阵?

时间:2019-08-10 06:28:15

标签: python sparse-matrix

我想在python中生成给定形状的稀疏厄米矩阵。我如何有效地做到这一点?这个任务有内置的python函数吗?

我已经找到了一个随机稀疏矩阵的解决方案,但是我也希望矩阵也是Hermitian。这是我发现的随机稀疏矩阵的解决方案

import numpy as np
import scipy.stats as stats
import scipy.sparse as sparse
import matplotlib.pyplot as plt
np.random.seed((3,14159))

def sprandsym(n, density):
    rvs = stats.norm().rvs
    X = sparse.random(n, n, density=density, data_rvs=rvs)
    upper_X = sparse.triu(X) 
    result = upper_X + upper_X.T - sparse.diags(X.diagonal())
    return result

M = sprandsym(5000, 0.01)
print(repr(M))
# <5000x5000 sparse matrix of type '<class 'numpy.float64'>'
#   with 249909 stored elements in Compressed Sparse Row format>

# check that the matrix is symmetric. The difference should have no non-zero elements
assert (M - M.T).nnz == 0

statistic, pval = stats.kstest(M.data, 'norm')
# The null hypothesis is that M.data was drawn from a normal distribution.
# A small p-value (say, below 0.05) would indicate reason to reject the null hypothesis.
# Since `pval` below is > 0.05, kstest gives no reason to reject the hypothesis
# that M.data is normally distributed.
print(statistic, pval)
# 0.0015998040114 0.544538788914

fig, ax = plt.subplots(nrows=2)
ax[0].hist(M.data, normed=True, bins=50)
stats.probplot(M.data, dist='norm', plot=ax[1])
plt.show()

1 个答案:

答案 0 :(得分:2)

我们知道一个矩阵加上一个埃尔米特矩阵就是一个埃尔米特矩阵。因此,要确保您的最终矩阵B是埃尔米特氏,只需这样做

B = A + A.conj().T