【发布时间】:2019-08-09 12:50:03
【问题描述】:
我有一大组数据,我需要将一组样本与该数组的距离与该数组的所有其他元素的距离进行比较。下面是我的数据集的一个非常简单的示例。
import numpy as np
import scipy.spatial.distance as sd
data = np.array(
[[ 0.93825827, 0.26701143],
[ 0.99121108, 0.35582816],
[ 0.90154837, 0.86254049],
[ 0.83149103, 0.42222948],
[ 0.27309625, 0.38925281],
[ 0.06510739, 0.58445673],
[ 0.61469637, 0.05420098],
[ 0.92685408, 0.62715114],
[ 0.22587817, 0.56819403],
[ 0.28400409, 0.21112043]]
)
sample_indexes = [1,2,3]
# I'd rather not make this
other_indexes = list(set(range(len(data))) - set(sample_indexes))
sample_data = data[sample_indexes]
other_data = data[other_indexes]
# compare them
dists = sd.cdist(sample_data, other_data)
有没有办法为不是样本索引的索引索引一个 numpy 数组?在上面的示例中,我创建了一个名为 other_indexes 的列表。由于各种原因(大型数据集、线程、正在运行的系统上的内存量非常低等),我宁愿不必这样做。有没有办法做类似的事情..
other_data = data[ indexes not in sample_indexes]
我读到 numpy 掩码可以做到这一点,但我尝试过......
other_data = data[~sample_indexes]
这给了我一个错误。我必须创建一个面具吗?
【问题讨论】:
-
可以安排
data,使第一行N形成sample_data,其余的形成other_data吗?如果是这样,您可以使用返回 views 的基本切片定义sample_data和other_data。这将需要很少的额外内存,因为视图共享相同的底层数据。 -
另外,如果您的内存非常有限,您可以考虑使用np.memmap 创建基于文件的数组。