【发布时间】:2013-09-04 00:26:20
【问题描述】:
感谢 Philip Cloud 的伟大 answer to a previous question,我去挖掘了 scikit 中 pairwise_distances 的源代码。
相关部分是:
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 评论似乎暗示了这一点,但我想确保我没有发疯,因为没有信息性警报表明计算实际上不会被抛出,这似乎有点奇怪当您使用不在PAIRWISE_DISTANCE_FUNCTIONS 中的可调用函数传递n_jobs= -1 时并行化。
【问题讨论】:
标签: python scikit-learn