gpt4 book ai didi

python - 以下用于计算所有向量对之间的距离的代码有什么问题?

转载 作者:行者123 更新时间:2023-12-01 03:40:41 26 4
gpt4 key购买 nike

我正在尝试找出所有向量对之间的曼哈顿距离。

import numpy as np
import itertools

class vector:
def __init__(self):
self.a = 0
self.b = 0

c = vector()
d = vector()
l = vector()
m = vector()

e = [c,d]
n = [l,m]
o = np.array(n)
f = np.array(e)
p = itertools.product(o,f)
p = list(p)
def comp(x):
return (x[0].a-x[1].a) + (x[0].b-x[1].b)

g = np.vectorize(comp)
print g(p)

我收到错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2207, in __call__
return self._vectorize_call(func=func, args=vargs)
File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2270, in _vectorize_call
ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2232, in _get_ufunc_and_otypes
outputs = func(*inputs)
File "<stdin>", line 2, in comp
AttributeError: vector instance has no attribute '__getitem__'

最佳答案

我不得不说我会以不同的方式处理这个问题。数值 Python 不能很好地处理 Python 类等。

你的类(class)

class vector:
def __init__(self):
self.a = 0
self.b = 0

基本上是一个长度为2的向量。因此,如果您要对许多长度为 2 的向量进行操作,我建议如下:

In [13]: p = np.array([[1, 2], [3, 4], [5, 6]])

In [14]: p
Out[14]:
array([[1, 2],
[3, 4],
[5, 6]])

每一行都是一个长度为 2 的向量。有 3 个这样的向量。这比 Python 类的 Python 列表 高效得多。

现在你的comp函数

def comp(x):
return (x[0].a-x[1].a) + (x[0].b-x[1].b)

基本上相当于

def comp(x):
return (x[0].a+x[0].b) - (x[1].a+x[1].b)

即第一个向量的分量和减去第二个向量的分量和。既然如此,您可以通过以下方式有效地计算成对输出

In [15]: q = p.sum(axis=1)

用于计算每个向量的分量和,后面是

In [16]: np.subtract.outer(q, q)
Out[16]:
array([[ 0, -4, -8],
[ 4, 0, -4],
[ 8, 4, 0]])

关于python - 以下用于计算所有向量对之间的距离的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com