數值計算·第六集:最小二乘問題(CVXPY版)

Least-squares(最小二乘)

標準形式:-In a least-squares, or linear regression, problem, we have measurements A \in \mathbb{R}^{m \times n} and b\in \mathbb{R} ^m and seek a vector x∈Rn x \in \mathbb{R}^n such that Ax is close to b. Closeness is defined as the sum of the squared differences:

#example -Least squares
import cvxpy as cp
import numpy as np

#problem data
m,n = 100,9
np.random.seed(1)
A = np.random.randn(m,n)
b = np.random.randn(m)

#problem variable
x = cp.Variable(n)
#print(x.shape)

#constraints
#constraints = [0<=x,x<=1]

#objective
objective = cp.Minimize(cp.sum_squares(A*x-b))

#construct the least squares problem
#prob = cp.Problem(objective,constraints)
prob = cp.Problem(objective)

#sovle the problem
#prob.solve(solver=cp.SCS, verbose=True, use_indirect=True)
prob.solve(solver = cp.OSQP,verbose = True)

#expression
if prob.status == cp.OPTIMAL:
    print("x = %s"%x.value)
    print('Min-Value = %s'%prob.value)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章