本文整理汇总了Python中scipy.spatial.distance.cityblock方法的典型用法代码示例。如果您正苦于以下问题:Python distance.cityblock方法的具体用法?Python distance.cityblock怎么用?Python distance.cityblock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.spatial.distance
的用法示例。
在下文中一共展示了distance.cityblock方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: manhattan_distance
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def manhattan_distance(vec1, vec2, weights=None):
"""
Manhattan distance.
Args:
vec1 (list): Vector 1. List of integer or float.
vec2 (list): Vector 2. List of integer or float. It should have the same length to vec1.
weights (list): Weights for each value in vectors. If it's None, all weights will be 1.0. Defaults to None.
Returns:
float: Manhattan distance.
"""
utils.check_for_none(vec1, vec2)
utils.check_for_type(list, vec1, vec2)
if weights:
utils.check_for_type(list, weights)
if len(vec1) != len(vec2):
raise ValueError('vec1 and vec2 should have same length')
return cityblock(vec1, vec2, weights)
示例2: __calc_distances__
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def __calc_distances__(self, v1s, v2s, is_sparse=True):
if is_sparse:
dcosine = np.array([cosine(x.toarray(), y.toarray()) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dcityblock = np.array([cityblock(x.toarray(), y.toarray()) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dcanberra = np.array([canberra(x.toarray(), y.toarray()) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
deuclidean = np.array([euclidean(x.toarray(), y.toarray()) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dminkowski = np.array([minkowski(x.toarray(), y.toarray(), 3) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dbraycurtis = np.array([braycurtis(x.toarray(), y.toarray()) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dskew_q1 = [skew(x.toarray().ravel()) for x in v1s]
dskew_q2 = [skew(x.toarray().ravel()) for x in v2s]
dkur_q1 = [kurtosis(x.toarray().ravel()) for x in v1s]
dkur_q2 = [kurtosis(x.toarray().ravel()) for x in v2s]
dskew_diff = np.abs(np.array(dskew_q1) - np.array(dskew_q2)).reshape((-1,1))
dkur_diff = np.abs(np.array(dkur_q1) - np.array(dkur_q2)).reshape((-1,1))
else:
dcosine = np.array([cosine(x, y) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dcityblock = np.array([cityblock(x, y) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dcanberra = np.array([canberra(x, y) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
deuclidean = np.array([euclidean(x, y) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dminkowski = np.array([minkowski(x, y, 3) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dbraycurtis = np.array([braycurtis(x, y) for (x, y) in zip(v1s, v2s)]).reshape((-1,1))
dskew_q1 = [skew(x) for x in v1s]
dskew_q2 = [skew(x) for x in v2s]
dkur_q1 = [kurtosis(x) for x in v1s]
dkur_q2 = [kurtosis(x) for x in v2s]
dskew_diff = np.abs(np.array(dskew_q1) - np.array(dskew_q2)).reshape((-1,1))
dkur_diff = np.abs(np.array(dkur_q1) - np.array(dkur_q2)).reshape((-1,1))
return np.hstack((dcosine,dcityblock,dcanberra,deuclidean,dminkowski,dbraycurtis,dskew_diff,dkur_diff))
示例3: test_pairwise_distances_chunked
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def test_pairwise_distances_chunked():
# Test the pairwise_distance helper function.
rng = np.random.RandomState(0)
# Euclidean distance should be equivalent to calling the function.
X = rng.random_sample((400, 4))
check_pairwise_distances_chunked(X, None, working_memory=1,
metric='euclidean')
# Test small amounts of memory
for power in range(-16, 0):
check_pairwise_distances_chunked(X, None, working_memory=2 ** power,
metric='euclidean')
# X as list
check_pairwise_distances_chunked(X.tolist(), None, working_memory=1,
metric='euclidean')
# Euclidean distance, with Y != X.
Y = rng.random_sample((200, 4))
check_pairwise_distances_chunked(X, Y, working_memory=1,
metric='euclidean')
check_pairwise_distances_chunked(X.tolist(), Y.tolist(), working_memory=1,
metric='euclidean')
# absurdly large working_memory
check_pairwise_distances_chunked(X, Y, working_memory=10000,
metric='euclidean')
# "cityblock" uses scikit-learn metric, cityblock (function) is
# scipy.spatial.
check_pairwise_distances_chunked(X, Y, working_memory=1,
metric='cityblock')
# Test that a value error is raised if the metric is unknown
assert_raises(ValueError, next,
pairwise_distances_chunked(X, Y, metric="blah"))
# Test precomputed returns all at once
D = pairwise_distances(X)
gen = pairwise_distances_chunked(D,
working_memory=2 ** -16,
metric='precomputed')
assert isinstance(gen, GeneratorType)
assert next(gen) is D
assert_raises(StopIteration, next, gen)
示例4: __init__
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def __init__(self, rad):
super().__init__(rad)
self.mask_ = np.zeros((2*rad+1, 2*rad+1, 2*rad+1), dtype=np.bool)
for r1 in range(2*self.rad+1):
for r2 in range(2*self.rad+1):
for r3 in range(2*self.rad+1):
if(cityblock((r1, r2, r3),
(self.rad, self.rad, self.rad)) <= self.rad):
self.mask_[r1, r2, r3] = True
示例5: test_cityblock_batch
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def test_cityblock_batch(random_matrix):
X = random_matrix
y = X[np.random.choice(X.shape[0])]
batch_dists = cityblock_batch(X, y)
single_dists = np.array([cityblock(x, y) for x in X]).reshape(X.shape[0], -1)
assert np.allclose(batch_dists, single_dists)
示例6: getDistLambda
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def getDistLambda(metric):
if (metric == "manhattan"):
return lambda x,y : distance.cityblock(x,y)
elif (metric == "cosine"):
return lambda x,y : distance.cosine(x,y)
else:
return lambda x,y : distance.euclidean(x,y)
示例7: get_distance_function
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def get_distance_function(requested_metric):
"""
This function returns a specified distance function.
Paramters
---------
requested_metric: str
Distance function. Can be any function in: https://docs.scipy.org/doc/scipy/reference/spatial.distance.html.
Returns
-------
requested_metric : distance function
"""
distance_options = {
'braycurtis': distance.braycurtis,
'canberra': distance.canberra,
'chebyshev': distance.chebyshev,
'cityblock': distance.cityblock,
'correlation': distance.correlation,
'cosine': distance.cosine,
'euclidean': distance.euclidean,
'sqeuclidean': distance.sqeuclidean,
'dice': distance.dice,
'hamming': distance.hamming,
'jaccard': distance.jaccard,
'kulsinski': distance.kulsinski,
'matching': distance.matching,
'rogerstanimoto': distance.rogerstanimoto,
'russellrao': distance.russellrao,
'sokalmichener': distance.sokalmichener,
'sokalsneath': distance.sokalsneath,
'yule': distance.yule,
}
if requested_metric in distance_options:
return distance_options[requested_metric]
else:
raise ValueError('Distance function cannot be found.')
示例8: manhattan_distance
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def manhattan_distance(self, privileged=None, returned=False):
"""Compute the average Manhattan distance between the samples from the
two datasets.
"""
condition = self._to_condition(privileged)
distance, mask = utils.compute_distance(self.dataset.features,
self.distorted_dataset.features, self.dataset.protected_attributes,
self.dataset.protected_attribute_names, dist_fun=scdist.cityblock,
condition=condition)
if returned:
return distance, self.dataset.instance_weights[mask]
return distance
示例9: get_node_distance_matrix
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def get_node_distance_matrix(self, datapoint, som_array):
"""Get distance of datapoint and node using Euclidean distance.
Parameters
----------
datapoint : np.array, shape=(X.shape[1])
Datapoint = one row of the dataset `X`
som_array : np.array
Weight vectors of the SOM,
shape = (self.n_rows, self.n_columns, X.shape[1])
Returns
-------
distmat : np.array of float
Distance between datapoint and each SOM node
"""
# algorithms on the full matrix
if self.distance_metric == "euclidean":
return np.linalg.norm(som_array - datapoint, axis=2)
# node-by-node algorithms
distmat = np.zeros((self.n_rows, self.n_columns))
if self.distance_metric == "manhattan":
for node in self.node_list_:
distmat[node] = dist.cityblock(
som_array[node[0], node[1]], datapoint)
elif self.distance_metric == "mahalanobis":
for node in self.node_list_:
som_node = som_array[node[0], node[1]]
cov = np.cov(np.stack((datapoint, som_node), axis=0),
rowvar=False)
cov_pinv = np.linalg.pinv(cov) # pseudo-inverse
distmat[node] = dist.mahalanobis(
datapoint, som_node, cov_pinv)
elif self.distance_metric == "tanimoto":
# Note that this is a binary distance measure.
# Therefore, the vectors have to be converted.
# Source: Melssen 2006, Supervised Kohonen networks for
# classification problems
# VERY SLOW ALGORITHM!!!
threshold = 0.5
for node in self.node_list_:
som_node = som_array[node[0], node[1]]
distmat[node] = dist.rogerstanimoto(
binarize(datapoint.reshape(1, -1), threshold, copy=True),
binarize(som_node.reshape(1, -1), threshold, copy=True))
return distmat
示例10: sliced_wasserstein
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import cityblock [as 别名]
def sliced_wasserstein(PD1, PD2, M=50):
""" Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)
Parameters
-----------
PD1: np.array size (m,2)
Persistence diagram
PD2: np.array size (n,2)
Persistence diagram
M: int, default is 50
Iterations to run approximation.
Returns
--------
sw: float
Sliced Wasserstein distance between PD1 and PD2
"""
diag_theta = np.array(
[np.cos(0.25 * np.pi), np.sin(0.25 * np.pi)], dtype=np.float32
)
l_theta1 = [np.dot(diag_theta, x) for x in PD1]
l_theta2 = [np.dot(diag_theta, x) for x in PD2]
if (len(l_theta1) != PD1.shape[0]) or (len(l_theta2) != PD2.shape[0]):
raise ValueError("The projected points and origin do not match")
PD_delta1 = [[np.sqrt(x ** 2 / 2.0)] * 2 for x in l_theta1]
PD_delta2 = [[np.sqrt(x ** 2 / 2.0)] * 2 for x in l_theta2]
# i have the input now to compute the sw
sw = 0
theta = 0.5
step = 1.0 / M
for i in range(M):
l_theta = np.array(
[np.cos(theta * np.pi), np.sin(theta * np.pi)], dtype=np.float32
)
V1 = [np.dot(l_theta, x) for x in PD1] + [np.dot(l_theta, x) for x in PD_delta2]
V2 = [np.dot(l_theta, x) for x in PD2] + [np.dot(l_theta, x) for x in PD_delta1]
sw += step * cityblock(sorted(V1), sorted(V2))
theta += step
return sw