本文整理汇总了Python中scipy.spatial.distance.euclidean方法的典型用法代码示例。如果您正苦于以下问题:Python distance.euclidean方法的具体用法?Python distance.euclidean怎么用?Python distance.euclidean使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.spatial.distance
的用法示例。
在下文中一共展示了distance.euclidean方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: eye_aspect_ratio
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def eye_aspect_ratio(eye):
# compute the euclidean distances between the two sets of
# vertical eye landmarks (x, y)-coordinates
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
# compute the euclidean distance between the horizontal
# eye landmark (x, y)-coordinates
C = dist.euclidean(eye[0], eye[3])
# compute the eye aspect ratio
ear = (A + B) / (2.0 * C)
# return the eye aspect ratio
return ear
# construct the argument parse and parse the arguments
示例2: _get_sorted_db_keypoint_distances
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def _get_sorted_db_keypoint_distances(self, N=None):
"""Use a minimum spanning tree heuristic to find the N largest gaps in the
line constituted by the current decision boundary keypoints.
"""
if N == None:
N = self.n_interpolated_keypoints
edges = minimum_spanning_tree(
squareform(pdist(self.decision_boundary_points_2d))
)
edged = np.array(
[
euclidean(
self.decision_boundary_points_2d[u],
self.decision_boundary_points_2d[v],
)
for u, v in edges
]
)
gap_edge_idx = np.argsort(edged)[::-1][: int(N)]
edges = edges[gap_edge_idx]
gap_distances = np.square(edged[gap_edge_idx])
gap_probability_scores = gap_distances / np.sum(gap_distances)
return edges, gap_distances, gap_probability_scores
示例3: setParameters
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def setParameters(self, NP=43, alpha=(1, 0.83), gamma=(1.17, 0.56), theta=(0.932, 0.832), d=euclidean, dn=euclidean, nl=1, F=1.2, CR=0.25, Combination=Elitism, **ukwargs):
r"""Set the parameters for the algorith.
Arguments:
alpha (Optional[List[float]]): Factor for fickleness index function :math:`\in [0, 1]`.
gamma (Optional[List[float]]): Factor for external irregularity index function :math:`\in [0, \infty)`.
theta (Optional[List[float]]): Factor for internal irregularity index function :math:`\in [0, \infty)`.
d (Optional[Callable[[float, float], float]]): function that takes two arguments that are function values and calcs the distance between them.
dn (Optional[Callable[[numpy.ndarray, numpy.ndarray], float]]): function that takes two arguments that are points in function landscape and calcs the distance between them.
nl (Optional[float]): Normalized range for neighborhood search :math:`\in (0, 1]`.
F (Optional[float]): Mutation parameter.
CR (Optional[float]): Crossover parameter :math:`\in [0, 1]`.
Combination (Optional[Callable[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, float, float, float, float, float, float, Task, mtrand.RandomState]]): Function for combining individuals to get new position/individual.
See Also:
* :func:`NiaPy.algorithms.Algorithm.setParameters`
* Combination methods:
* :func:`NiaPy.algorithms.other.Elitism`
* :func:`NiaPy.algorithms.other.Crossover`
* :func:`NiaPy.algorithms.other.Sequential`
"""
Algorithm.setParameters(self, NP=NP, **ukwargs)
self.alpha, self.gamma, self.theta, self.d, self.dn, self.nl, self.F, self.CR, self.Combination = alpha, gamma, theta, d, dn, nl, F, CR, Combination
示例4: setParameters
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def setParameters(self, N=25, phi=0.4, Fa=0.5, Fb=0.5, Fd=0.3, k=25, P_Cr=0.5, P_F=0.36, SexualCrossover=SexualCrossoverSimple, Brooding=BroodingSimple, Distance=euclidean, **ukwargs):
r"""Set the parameters of the algorithm.
Arguments:
N (int): population size for population initialization.
phi (int): TODO.
Fa (float): Value $\in [0, 1]$ for Asexual reproduction size.
Fb (float): Value $\in [0, 1]$ for Brooding size.
Fd (float): Value $\in [0, 1]$ for Depredation size.
k (int): Trys for larvae setting.
SexualCrossover (Callable[[numpy.ndarray, float, Task, mtrand.RandomState, Dict[str, Any]], Tuple[numpy.ndarray, numpy.ndarray]]): Crossover function.
P_Cr (float): Crossover rate $\in [0, 1]$.
Brooding (Callable[[numpy.ndarray, float, Task, mtrand.RandomState, Dict[str, Any]], Tuple[numpy.ndarray, numpy.ndarray]]): Brooding function.
P_F (float): Crossover rate $\in [0, 1]$.
Distance (Callable[[numpy.ndarray, numpy.ndarray], float]): Funciton for calculating distance between corals.
See Also:
* :func:`NiaPy.algorithms.Algorithm.setParameters`
"""
ukwargs.pop('NP', None)
Algorithm.setParameters(self, NP=N, **ukwargs)
self.phi, self.k, self.P_Cr, self.P_F = phi, k, P_Cr, P_F
self.Fa, self.Fb, self.Fd = int(self.NP * Fa), int(self.NP * Fb), int(self.NP * Fd)
self.SexualCrossover, self.Brooding, self.Distance = SexualCrossover, Brooding, Distance
示例5: setParameters
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def setParameters(self, n=25, l0=5, nt=5, rho=0.4, gamma=0.6, beta=0.08, s=0.03, Distance=euclidean, **ukwargs):
r"""Set the arguments of an algorithm.
Arguments:
n (Optional[int]): Number of glowworms in population.
l0 (Optional[float]): Initial luciferin quantity for each glowworm.
nt (Optional[float]): --
rs (Optional]float]): Maximum sensing range.
rho (Optional[float]): Luciferin decay constant.
gamma (Optional[float]): Luciferin enhancement constant.
beta (Optional[float]): --
s (Optional[float]): --
Distance (Optional[Callable[[numpy.ndarray, numpy.ndarray], float]]]): Measure distance between two individuals.
"""
ukwargs.pop('NP', None)
Algorithm.setParameters(self, NP=n, **ukwargs)
self.l0, self.nt, self.rho, self.gamma, self.beta, self.s, self.Distance = l0, nt, rho, gamma, beta, s, Distance
示例6: initPopulation
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def initPopulation(self, task):
r"""Initialize population.
Args:
task (Task): Optimization task.
Returns:
Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:
1. Initialized population of glowwarms.
2. Initialized populations function/fitness values.
3. Additional arguments:
* L (numpy.ndarray): TODO.
* R (numpy.ndarray): TODO.
* rs (numpy.ndarray): TODO.
"""
GS, GS_f, d = Algorithm.initPopulation(self, task)
rs = euclidean(full(task.D, 0), task.bRange)
L, R = full(self.NP, self.l0), full(self.NP, rs)
d.update({'L': L, 'R': R, 'rs': rs})
return GS, GS_f, d
示例7: selection
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def selection(self, pop, npop, xb, fxb, task, **kwargs):
r"""Operator for selection of individuals.
Args:
pop (numpy.ndarray): Current population.
npop (numpy.ndarray): New population.
xb (numpy.ndarray): Current global best solution.
fxb (float): Current global best solutions fitness/objective value.
task (Task): Optimization task.
kwargs (Dict[str, Any]): Additional arguments.
Returns:
Tuple[numpy.ndarray, numpy.ndarray, float]:
1. New population.
2. New global best solution.
3. New global best solutions fitness/objective value.
"""
P = []
for e in npop:
i = argmin([euclidean(e, f) for f in pop])
P.append(pop[i] if pop[i].f < e.f else e)
return asarray(P), xb, fxb
示例8: point_list_filter
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def point_list_filter(
point_list: typing.Sequence, distance: float, point_limit: int = None
) -> typing.Sequence:
""" remove some points which are too close """
if not point_limit:
point_limit = 20
point_list = sorted(list(set(point_list)), key=lambda o: o[0])
new_point_list = [point_list[0]]
for cur_point in point_list[1:]:
for each_confirmed_point in new_point_list:
cur_distance = euclidean(cur_point, each_confirmed_point)
# existed
if cur_distance < distance:
break
else:
new_point_list.append(cur_point)
if len(new_point_list) >= point_limit:
break
return new_point_list
示例9: compute_density_estimator
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def compute_density_estimator(self, solutions: List[S]):
solutions_size = len(solutions)
if solutions_size <= self.k:
return
points = []
for i in range(solutions_size):
points.append(solutions[i].objectives)
# Compute distance matrix
self.distance_matrix = numpy.zeros(shape=(solutions_size, solutions_size))
for i in range(solutions_size):
for j in range(solutions_size):
self.distance_matrix[i, j] = self.distance_matrix[j, i] = euclidean(solutions[i].objectives,
solutions[j].objectives)
# Gets the k-nearest distance of all the solutions
for i in range(solutions_size):
distances = []
for j in range(solutions_size):
distances.append(self.distance_matrix[i, j])
distances.sort()
solutions[i].attributes['knn_density'] = distances[self.k]
示例10: word_mover_distance
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def word_mover_distance(first_sent_tokens, second_sent_tokens, wvmodel, distancefunc=euclidean, lpFile=None):
""" Compute the Word Mover's distance (WMD) between the two given lists of tokens.
Using methods of linear programming, supported by PuLP, calculate the WMD between two lists of words. A word-embedding
model has to be provided. WMD is returned.
Reference: Matt J. Kusner, Yu Sun, Nicholas I. Kolkin, Kilian Q. Weinberger, "From Word Embeddings to Document Distances," *ICML* (2015).
:param first_sent_tokens: first list of tokens.
:param second_sent_tokens: second list of tokens.
:param wvmodel: word-embedding models.
:param distancefunc: distance function that takes two numpy ndarray.
:param lpFile: log file to write out.
:return: Word Mover's distance (WMD)
:type first_sent_tokens: list
:type second_sent_tokens: list
:type wvmodel: gensim.models.keyedvectors.KeyedVectors
:type distancefunc: function
:type lpFile: str
:rtype: float
"""
prob = word_mover_distance_probspec(first_sent_tokens, second_sent_tokens, wvmodel,
distancefunc=distancefunc, lpFile=lpFile)
return pulp.value(prob.objective)
示例11: test_dbscan_feature
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def test_dbscan_feature():
# Tests the DBSCAN algorithm with a feature vector array.
# Parameters chosen specifically for this task.
# Different eps to other test, because distance is not normalised.
eps = 0.8
min_samples = 10
metric = 'euclidean'
# Compute DBSCAN
# parameters chosen for task
core_samples, labels = dbscan(X, metric=metric, eps=eps,
min_samples=min_samples)
# number of clusters, ignoring noise if present
n_clusters_1 = len(set(labels)) - int(-1 in labels)
assert_equal(n_clusters_1, n_clusters)
db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples)
labels = db.fit(X).labels_
n_clusters_2 = len(set(labels)) - int(-1 in labels)
assert_equal(n_clusters_2, n_clusters)
示例12: test_dbscan_callable
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def test_dbscan_callable():
# Tests the DBSCAN algorithm with a callable metric.
# Parameters chosen specifically for this task.
# Different eps to other test, because distance is not normalised.
eps = 0.8
min_samples = 10
# metric is the function reference, not the string key.
metric = distance.euclidean
# Compute DBSCAN
# parameters chosen for task
core_samples, labels = dbscan(X, metric=metric, eps=eps,
min_samples=min_samples,
algorithm='ball_tree')
# number of clusters, ignoring noise if present
n_clusters_1 = len(set(labels)) - int(-1 in labels)
assert_equal(n_clusters_1, n_clusters)
db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples,
algorithm='ball_tree')
labels = db.fit(X).labels_
n_clusters_2 = len(set(labels)) - int(-1 in labels)
assert_equal(n_clusters_2, n_clusters)
示例13: gap
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def gap(data, refs=None, nrefs=20, ks=range(1,11), method=None):
shape = data.shape
if refs is None:
tops = data.max(axis=0)
bots = data.min(axis=0)
dists = scipy.matrix(scipy.diag(tops-bots))
rands = scipy.random.random_sample(size=(shape[0], shape[1], nrefs))
for i in range(nrefs):
rands[:, :, i] = rands[:, :, i]*dists+bots
else:
rands = refs
gaps = scipy.zeros((len(ks),))
for (i, k) in enumerate(ks):
g1 = method(n_clusters=k).fit(data)
(kmc, kml) = (g1.cluster_centers_, g1.labels_)
disp = sum([euclidean(data[m, :], kmc[kml[m], :]) for m in range(shape[0])])
refdisps = scipy.zeros((rands.shape[2],))
for j in range(rands.shape[2]):
g2 = method(n_clusters=k).fit(rands[:, :, j])
(kmc, kml) = (g2.cluster_centers_, g2.labels_)
refdisps[j] = sum([euclidean(rands[m, :, j], kmc[kml[m],:]) for m in range(shape[0])])
gaps[i] = scipy.log(scipy.mean(refdisps))-scipy.log(disp)
return gaps
示例14: get_ear
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def get_ear(eye):
# compute the euclidean distances between the two sets of
# vertical eye landmarks (x, y)-coordinates
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
# compute the euclidean distance between the horizontal
# eye landmark (x, y)-coordinates
C = dist.euclidean(eye[0], eye[3])
# compute the eye aspect ratio
ear = (A + B) / (2.0 * C)
# return the eye aspect ratio
return ear
示例15: kMeansClustering
# 需要导入模块: from scipy.spatial import distance [as 别名]
# 或者: from scipy.spatial.distance import euclidean [as 别名]
def kMeansClustering(x,k):
# Convert list into numpy format
conv = np.asarray(x)
# Compute the centroids
centroids = kmeans(conv,k,iter=10)[0]
# Relabel the x's
labels = []
for y in range(len(x)):
minDist = float('inf')
minLabel = -1
for z in range(len(centroids)):
e = euclidean(conv[y],centroids[z])
if (e < minDist):
minDist = e
minLabel = z
labels.append(minLabel)
# Return the list of centroids and labels
return (centroids,labels)
# Performs a weighted clustering on the examples in xTest
# Returns a 1-d vector of predictions