Least squares with fixed coefficient magnitude

Quick and easy, here's some code that performs least squares, with the condition that the coefficient vector has a particular magnitude. I offer no proof for this, I just had the intuition that it would work and it did. It's an intermediary step in some other code but it's useful all by itself.

def sphere_least_squares(X,b,magnitude=1):
    u,s,vt = np.linalg.svd(X, full_matrices=False)
    scale_coeffs = (u.T @ b)/s
    sq_scale_coeffs = (scale_coeffs)**2
    lc = np.argwhere(np.cumsum((sq_scale_coeffs))>magnitude)[0,0]#first_coeff exceeding magnitude
    scale_coeffs[lc] *= np.sqrt((magnitude-np.sum(sq_scale_coeffs[:lc]))/sq_scale_coeffs[lc])
    c = vt.T[:,:(lc+1)] @ scale_coeffs[:(lc+1)]
    return c

No comments:

Post a Comment

March thoughts

Lets start by taking any system of ordinary differential equations. We can of course convert this to a first order system by creating stand-...