如何在 python 中生成随机稀疏厄米矩阵?
How to generate a Random Sparse Hermitian Matrix in python?
我想在 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()
我们知道一个矩阵加上它的厄密矩阵就是厄密矩阵。因此,为确保您的最终矩阵 B
是厄尔米特矩阵,只需执行
B = A + A.conj().T
我想在 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()
我们知道一个矩阵加上它的厄密矩阵就是厄密矩阵。因此,为确保您的最终矩阵 B
是厄尔米特矩阵,只需执行
B = A + A.conj().T