Skip to content

Instantly share code, notes, and snippets.

@SwampThingPaul
Forked from RyotaBannai/tls.py
Created January 3, 2019 20:07
Show Gist options
  • Save SwampThingPaul/c11b8698da92e8a89fa00b42bbb24d8f to your computer and use it in GitHub Desktop.
Save SwampThingPaul/c11b8698da92e8a89fa00b42bbb24d8f to your computer and use it in GitHub Desktop.
import numpy.linalg as la
def tls(X,y):
if X.ndim is 1:
n = 1 # the number of variable of X
X = X.reshape(len(X),1)
else:
n = np.array(X).shape[1]
Z = np.vstack((X.T,y)).T
U, s, Vt = la.svd(Z, full_matrices=True)
V = Vt.T
Vxy = V[:n,n:]
Vyy = V[n:,n:]
a_tls = - Vxy / Vyy # total least squares soln
Xtyt = - Z.dot(V[:,n:]).dot(V[:,n:].T)
Xt = Xtyt[:,:n] # X error
y_tls = (X+Xt).dot(a_tls)
fro_norm = la.norm(Xtyt, 'fro')
return y_tls, X+Xt, a_tls, fro_norm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment