【发布时间】:2021-07-23 21:45:02
【问题描述】:
需要一个执行类似于numpy.where 函数的函数,但不会遇到由布尔数组的密集表示引起的内存问题。因此,该函数应该能够返回一个极其稀疏的布尔数组。
虽然下面给出的示例适用于小型数据集/向量,但不可能使用 numpy.where 函数,例如,my_sample 的形状为 (10.000.000, 1) 和 my_population 的形状为 @987654327 @。阅读其他线程后,numpy.where 在评估表达式numpy.where((my_sample == my_population.T)) 时显然创建了一个形状为(10.000.000, 100.000) 的密集布尔数组。这个密集的(10.000.000, 100.000) 数组无法放入我的机器/大多数机器的内存中。
生成的数组非常稀疏。就我而言,要知道每行最多有两个 1!使用上面的规范,稀疏度等于 0.002%。这绝对应该适合记忆。
尝试为数值模拟创建类似于模型/设计矩阵的东西。生成的矩阵将用于一些线性代数运算。
最小的工作示例:请注意向量中的位置/坐标很重要。
# import packages
import numpy as np
# my_sample is the vector of observations
my_sample = ['a', 'b', 'c', 'a']
# my_population is the lookup vector
my_population = ['a', 'b', 'c']
# initalise the matrix (dense matrix for this exampe)
my_zero = np.zeros((len(my_sample), len(my_population)))
# reshape to arrays
my_sample = np.array(my_sample).reshape(-1, 1)
my_population = np.array((my_population)).reshape(-1, 1)
# THIS STEP CAUSES THE MEMORY ISSUES
my_indices = np.where((my_sample == my_population.T))
# set the matches to equal one
my_zero[my_indices] = 1
# show matrix
my_zero
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.],
[1., 0., 0.]])
【问题讨论】:
-
您在寻找“更好的性能”吗?如果是这样,您可以尝试使用
numba。这样做有很多好处 -
@JohnBrookfields 我正在寻找一种适合普通机器内存的解决方案(比如 16GB 的 RAM)。但是感谢您指出这一点,我将编辑我的问题。
-
numba也有内存管理。见here -
需要明确的是,
==操作占用了大量内存。where只是找到该数组的True元素。 -
@hpaulj 非常感谢您的澄清!
标签: python numpy scipy sparse-matrix elementwise-operations