如何解决为什么 np.linalg.norm 在这里产生错误?
我正在尝试使用 cvxpy 解决经典的最小二乘问题,但由于 np.linalg.norm
出现错误。任何帮助将不胜感激。
我的代码如下。就这样,它有效。但是,如果我将 cp.sum_squares
更改为 np.linalg.norm
,它不起作用(错误消息吹)。
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)
错误信息:
"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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。