def dist_matrices(X1, X2, criterion='euclidean'):
X1loc = np.array(X1)
X2loc = np.array(X2)
if len(X1loc.shape) == 1:
if len(X2loc.shape) == 1:
if X1loc.shape[0] == X2loc.shape[0]:
# As row vectors
X1loc = X1loc.reshape(1, -1)
X2loc = X2loc.reshape(1, -1)
else:
# As column vectors
X1loc = X1loc.reshape(-1, 1)
X2loc = X2loc.reshape(-1, 1)
else:
if X1loc.shape[0] == X2loc.shape[1]:
# Row vector VS. Many rows
X1loc = X1loc.reshape(1, -1)
elif X2loc.shape[1] == 1:
# Column vector VS. Column vector
X1loc = X1loc.reshape(-1, 1)
elif X1loc.shape[0] == X2loc.shape[0]:
# Row vector VS. transposed columns
X1loc = X1loc.reshape(1, -1)
X2loc = X2loc.transpose()
else:
raise ValueError('Invalid dimensions of X1 and X2')
elif len(X2loc.shape) == 1:
if X2loc.shape[0] == X1loc.shape[1]:
# Many rows VS. row vector
X2loc = X2loc.reshape(1, -1)
else:
raise ValueError('Invalid dimensions of X1 and X2')
if criterion == 'euclidean':
return skdists.euclidean_distances(X1loc, X2loc)
elif criterion == 'hamming':
raise NotImplementedError('Hamming distance between rows of matrices has not been implemented yet.')
else:
raise ValueError('Invalid distance criterion')
评论列表
文章目录