简体   繁体   English

<lambda>() 接受 1 个位置参数,但给出了 2 个

[英]<lambda>() takes 1 positional argument but 2 were given

I am trying to implement the same Sage code here: find vector center in python, as follows:我试图在这里实现相同的 Sage 代码:在 python 中找到向量中心,如下:

import numpy as np
from scipy.optimize import minimize
def norm(x):
    return x/np.linalg.norm(x)

vectors = np.array([[1,2,3],[4,5,6],[7,8,9]])
unit_vectors = [np.divide(v,norm(v)) for v in vectors]
constraints = [lambda x: np.dot(x,u)-1 for u in unit_vectors]
target = lambda x: norm(x)
res = minimize(target,[3,3,3],constraints)

But I keep getting the same problem:但我一直遇到同样的问题:

TypeError: <lambda>() takes 1 positional argument but 2 were given

I am not a mathematician, I just want to write a code that can find a center of multidimensional vectors.我不是数学家,我只是想写一个可以找到多维向量中心的代码。 I tried many things to solve the problem but nothing worked.我尝试了很多方法来解决问题,但没有任何效果。

Thanks.谢谢。

The algorithm of the answer that you indicate is not written in python, so which obviously can fail, considering the official docs I have implemented the following solution:您指出的答案的算法不是用 python 编写的,因此考虑我已经实现以下解决方案的官方文档,这显然可能会失败:

import numpy as np
from scipy.optimize import minimize


x0 = 10, 10, 10

vectors = [
    np.array([1, 2, 3]),
    np.array([1, 0, 2]),
    np.array([3, 2, 4]),
    np.array([5, 2, -1]),
    np.array([1, 1, -1]),
]

unit_vectors = [vector / np.linalg.norm(vector) for vector in vectors]
constraints = [
    {"type": "ineq", "fun": lambda x, u=u: (np.dot(x, u) - 1)} for u in unit_vectors
]

target = lambda x: np.linalg.norm(x)
res = minimize(fun=target, x0=x0, constraints=constraints)
print(res.x)

Output:输出:

[1.38118173 0.77831221 0.42744313]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM