How do I find solution of an under-constrained linear system in $\mathbb{R}^d$ that is closest to given reference $w_0$ in Euclidean distance?
Below is a solution that uses QuadraticOptimization
, however that requires writing out the formulas symbolically. For $d=1000$, there are 1 million symbolic variables, is there a more efficient approach?
norm2[mat_] := Total@Flatten[mat*mat];
modifiedLeastSquares[m_, b_, w0_] := Module[{xx, x, eqs, d},
d = Last@Dimensions[b];
x = Array[xx, {d, d}];
eqs = Flatten@MapThread[#1 == #2 &, {m . x, b}, 2];
x /. QuadraticOptimization[norm2[x - w0], eqs, Flatten@x]
];
SeedRandom[1];
bs = 4;
d = 8;
m = RandomReal[{-1, 1}, {bs, d}];
b = RandomReal[{-1, 1}, {bs, d}];
w0 = ConstantArray[0, {d, d}];
mySol = modifiedLeastSquares[m, b, w0];
refSol = LeastSquares[m, b];
Print["Difference from built-in LeastSquares: ",
mySol - refSol // Norm]
LeastSquares[ ]
tries to minimize $||mx-b||^{2}$, not $||x||^2$. Why do you use it as a reference? $\endgroup$LeastSquares
$\endgroup$LeastSquares
is misleading ..... $\endgroup$Norm[mat, "Frobenius"]
is built-in, but it's a tad slower (probably because it squares the absolute value of the entries). Andnorm2[mat_] := Total[mat*mat, 2]
is a tad faster than yournorm2[]
. $\endgroup$