如何处理巨大的 numpy 数组的计算以避免内存分配错误?

How to handle calculations on huge numpy array to avoid memory allocation error?

我需要一个大小为 (62500 x 62500) 的负单位矩阵。 使用 numpy 声明一个正常的单位矩阵就像一个魅力:

eye = np.eye(62500, 62500)

但是,做这样的事情

negative_eye1 = np.negative(np.eye(62500, 62500))
# or
negative_eye2 = np.eye(62500, 62500) * -1

会导致这个错误

Unable to allocate array with shape (62500, 62500) and data type float64

然后在 scipy.sparse.bmat() 函数中使用矩阵,生成 csr 矩阵,内存不再是这样的问题。

如何计算这个矩阵?

您可以使用 scipy.sparse.eye(对角线上有 1 的稀疏矩阵):

from scipy import sparse

negative_eye = -sparse.eye(62500, 62500)