100:
我试图计算两个大张量(对于k近邻)中每两个样本之间的成对距离,即给定形状为(b1,c,h,w)
的张量test
和形状为(b2,c,h,w)
的张量train
,每i
j
需要|| test[i]-train[j] ||
.(其中test[i]
和train[j]
都具有形状(c,h,w)
,因为它们是批次中的样本).
100
train
和test
都很大,所以我无法将它们放入RAM中
100
首先,我并没有一次性构造这些张量——在构建它们的过程中,我分割了数据张量,并将它们分别保存到内存中,因此我最终得到了文件{Test\test_1,...,Test\test_n}
和{Train\train_1,...,Train\train_m}
.
这个半伪代码可以解释
test_files = [f'Test\test_{i}' for i in range(n)]
train_files = [f'Train\train_{j}' for j in range(m)]
dist = lambda t1,t2: torch.cdist(t1.flatten(1), t2.flatten(1))
all_distances = []
for test_i in test_files:
test_i = torch.load(test_i) # shape (c,h,w)
dist_of_i_from_all_j = torch.Tensor([])
for train_j in train_files:
train_j = torch.load(train_j) # shape (c,h,w)
dist_of_i_from_all_j = torch.cat((dist_of_i_from_all_j, dist(test_i,train_j))
all_distances.append(dist_of_i_from_all_j)
# and now I can take the k-smallest from all_distances
100
我遇到了FAISS repository个,他们解释说这个过程可以加快(也许?)使用他们的解决方案,尽管我不太确定如何使用.无论如何,任何方法都会有帮助!