如何在Python中生成随机稀疏埃尔米特矩阵?

Pro*_*Nag 2 python sparse-matrix

我想在 python 中生成给定形状的随机稀疏埃尔米特矩阵。我怎样才能高效地做到这一点?有没有内置的Python函数可以完成这个任务?

我已经找到了随机稀疏矩阵的解决方案,但我也希望该矩阵是厄米特矩阵。这是我找到的随机稀疏矩阵的解决方案

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()
Run Code Online (Sandbox Code Playgroud)

Nil*_*ner 5

我们知道一个矩阵加上它的厄密矩阵就是厄密矩阵。所以为了确保你的最终矩阵B是埃尔米特矩阵,只需这样做

B = A + A.conj().T
Run Code Online (Sandbox Code Playgroud)