()接受1个位置参数,但给出2个位置参数

问题描述 投票:0回答:1

我试图在此处实现相同的Sage代码:python中的find vector center,如下所示:

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)

但是我仍然遇到相同的问题:

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

我不是数学家,我只想编写一个可以找到多维向量中心的代码。我尝试了很多方法来解决问题,但没有任何效果。

谢谢。

python numpy lambda constraints minimize
1个回答
0
投票

您指出的答案的算法不是用python编写的,因此考虑到the official docs,我已经实现了以下解决方案,因此显然可能会失败:

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)

输出:

[1.38118173 0.77831221 0.42744313]
© www.soinside.com 2019 - 2024. All rights reserved.