感谢 Philip Cloud对上一个问题的出色回答,我去挖掘了pairwise_distances
in scikit 的源代码。
相关部分是:
def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds):
if metric == "precomputed":
return X
elif metric in PAIRWISE_DISTANCE_FUNCTIONS:
func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
if n_jobs == 1:
return func(X, Y, **kwds)
else:
return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
elif callable(metric):
# Check matrices first (this is usually done by the metric).
X, Y = check_pairwise_arrays(X, Y)
n_x, n_y = X.shape[0], Y.shape[0]
# Calculate distance for each element in X and Y.
# FIXME: can use n_jobs here too
D = np.zeros((n_x, n_y), dtype='float')
for i in range(n_x):
start = 0
if X is Y:
start = i
for j in range(start, n_y):
# distance assumed to be symmetric.
D[i][j] = metric(X[i], Y[j], **kwds)
if X is Y:
D[j][i] = D[i][j]
return D
从中理解是否正确,如果我要计算成对距离矩阵,例如:
matrix = pairwise_distances(foo, metric=lambda u,v: haversine(u,v), n_jobs= -1)
哪里haversine(u,v)
有一个计算两点之间Haversine距离的函数,而这个函数不在,PAIRWISE_DISTANCE_FUNCTIONS
即使计算也不会并行化n_jobs= -1
?
我意识到#FIXME
评论似乎暗示了这一点,但我想确保我没有发疯,因为似乎有点奇怪,不会抛出信息警报,说明当你通过时计算实际上不会并行化n_jobs= -1
a不在的可调用函数PAIRWISE_DISTANCE_FUNCTIONS
。