Sarah N
Sarah N

Reputation: 43

<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:

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.

Upvotes: 4

Views: 10056

Answers (1)

eyllanesc
eyllanesc

Reputation: 244132

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:

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]

Upvotes: 5

Related Questions