I am trying to solve the classical Least Squares Problem using cvxpy, but I am getting an error due to np.linalg.norm
. Any help would be immensely appreciated.
My code is below. As it is, it works. However, if I change cp.sum_squares
to np.linalg.norm
, it does not work (error message blow).
import cvxpy as cp
import numpy as np
def main(n):
# Create the data for the least squares problem
A = np.random.rand(n, n-1)
b = np.random.rand(n)
# Introduce the variables
x = cp.Variable(n-1)
# Introduce the constraints (no constraints)
constraints = []
# Introduce the objective function
obj = cp.Minimize(cp.sum_squares(A @ x - b))
prob = cp.Problem(obj, constraints)
prob.solve()
main(4)
Error message:
"C:\Users\Ovi\Desktop\Python Files\venv\Scripts\python.exe" "C:/Users/Ovi/Desktop/Python Files/Solving Least Squares.py"
C:\Users\Ovi\Desktop\Python Files\venv\lib\site-packages\cvxpy\expressions\expression.py:556: UserWarning:
This use of ``*`` has resulted in matrix multiplication.
Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1.
Use ``*`` for matrix-scalar and vector-scalar multiplication.
Use ``@`` for matrix-matrix and matrix-vector multiplication.
Use ``multiply`` for elementwise multiplication.
This code path has been hit 1 times so far.
warnings.warn(msg, UserWarning)
AttributeError: 'MulExpression' object has no attribute 'sqrt'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ovi\Desktop\Python Files\Solving Least Squares.py", line 22, in <module>
main(4)
File "C:\Users\Ovi\Desktop\Python Files\Solving Least Squares.py", line 17, in main
obj = cp.Minimize(np.linalg.norm(A @ x - b))
File "<__array_function__ internals>", line 5, in norm
File "C:\Users\Ovi\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\linalg\linalg.py", line 2530, in norm
ret = sqrt(sqnorm)
TypeError: loop of ufunc does not support argument 0 of type MulExpression which has no callable sqrt method
Process finished with exit code 1