2007-07-28 11:18:48 +02:00
|
|
|
"""Module contain algorithms for low-rank models.
|
2006-12-18 12:59:12 +01:00
|
|
|
|
2007-07-28 11:18:48 +02:00
|
|
|
There is almost no typechecking of any kind here, just focus on speed
|
2006-12-18 12:59:12 +01:00
|
|
|
"""
|
|
|
|
|
2007-07-23 19:33:21 +02:00
|
|
|
import math
|
|
|
|
from scipy.linalg import svd,inv
|
2006-12-18 12:59:12 +01:00
|
|
|
from scipy import dot,empty,eye,newaxis,zeros,sqrt,diag,\
|
2007-07-28 18:05:11 +02:00
|
|
|
apply_along_axis,mean,ones,randn,empty_like,outer,r_,c_,\
|
2007-08-07 13:41:03 +02:00
|
|
|
rand,sum,cumsum,matrix, expand_dims,minimum,where,arange
|
2007-07-26 20:32:48 +02:00
|
|
|
has_sym=True
|
|
|
|
try:
|
2007-07-28 18:05:11 +02:00
|
|
|
from symeig import symeig
|
2007-07-26 20:32:48 +02:00
|
|
|
except:
|
|
|
|
has_sym = False
|
|
|
|
|
2007-07-30 20:04:42 +02:00
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
def pca(a, aopt,scale='scores',mode='normal',center_axis=0):
|
2007-07-28 18:05:11 +02:00
|
|
|
""" Principal Component Analysis.
|
|
|
|
|
|
|
|
Performs PCA on given matrix and returns results in a dictionary.
|
|
|
|
|
|
|
|
:Parameters:
|
|
|
|
a : array
|
|
|
|
Data measurement matrix, (samples x variables)
|
|
|
|
aopt : int
|
|
|
|
Number of components to use, aopt<=min(samples, variables)
|
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
:Returns:
|
2007-07-28 18:05:11 +02:00
|
|
|
results : dict
|
|
|
|
keys -- values, T -- scores, P -- loadings, E -- residuals,
|
|
|
|
lev --leverages, ssq -- sum of squares, expvar -- cumulative
|
|
|
|
explained variance, aopt -- number of components used
|
2006-12-18 12:59:12 +01:00
|
|
|
|
2007-08-24 11:14:24 +02:00
|
|
|
:OtherParam eters:
|
2007-07-28 18:05:11 +02:00
|
|
|
mode : str
|
|
|
|
Amount of info retained, ('fast', 'normal', 'detailed')
|
|
|
|
center_axis : int
|
|
|
|
Center along given axis. If neg.: no centering (-inf,..., matrix modes)
|
|
|
|
|
|
|
|
:SeeAlso:
|
|
|
|
- pcr : other blm
|
|
|
|
- pls : other blm
|
|
|
|
- lpls : other blm
|
2007-07-30 11:46:43 +02:00
|
|
|
|
2007-07-28 18:05:11 +02:00
|
|
|
Notes
|
|
|
|
-----
|
|
|
|
|
|
|
|
Uses kernel speed-up if m>>n or m<<n.
|
|
|
|
|
|
|
|
If residuals turn rank deficient, a lower number of component than given
|
2007-07-30 11:46:43 +02:00
|
|
|
in input will be used. The number of components used is given in
|
|
|
|
results-dict.
|
2007-07-28 18:05:11 +02:00
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
|
|
|
|
>>> import scipy,engines
|
|
|
|
>>> a=scipy.asarray([[1,2,3],[2,4,5]])
|
|
|
|
>>> dat=engines.pca(a, 2)
|
2007-07-30 11:46:43 +02:00
|
|
|
>>> dat['expvarx']
|
2007-07-28 18:05:11 +02:00
|
|
|
array([0.,99.8561562, 100.])
|
|
|
|
|
|
|
|
"""
|
2007-08-02 13:18:18 +02:00
|
|
|
m, n = a.shape
|
|
|
|
assert(aopt<=min(m,n))
|
2007-07-28 18:05:11 +02:00
|
|
|
if center_axis>=0:
|
|
|
|
a = a - expand_dims(a.mean(center_axis), center_axis)
|
2007-07-26 20:32:48 +02:00
|
|
|
if m>(n+100) or n>(m+100):
|
2007-08-07 13:41:03 +02:00
|
|
|
u, s, v = esvd(a, amax=None) # fixme:amax option need to work with expl.var
|
2007-01-25 13:17:16 +01:00
|
|
|
else:
|
2007-07-26 20:32:48 +02:00
|
|
|
u, s, vt = svd(a, 0)
|
2007-07-23 19:33:21 +02:00
|
|
|
v = vt.T
|
2007-08-07 13:41:03 +02:00
|
|
|
e = s**2
|
2007-07-28 18:05:11 +02:00
|
|
|
tol = 1e-10
|
|
|
|
eff_rank = sum(s>s[0]*tol)
|
|
|
|
aopt = minimum(aopt, eff_rank)
|
2006-12-18 12:59:12 +01:00
|
|
|
T = u*s
|
2007-07-28 18:05:11 +02:00
|
|
|
s = s[:aopt]
|
2006-12-18 12:59:12 +01:00
|
|
|
T = T[:,:aopt]
|
2007-07-23 19:33:21 +02:00
|
|
|
P = v[:,:aopt]
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
if scale=='loads':
|
2007-07-28 18:05:11 +02:00
|
|
|
T = T/s
|
|
|
|
P = P*s
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
if mode == 'fast':
|
2007-07-28 18:05:11 +02:00
|
|
|
return {'T':T, 'P':P, 'aopt':aopt}
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
if mode=='detailed':
|
2007-07-28 18:05:11 +02:00
|
|
|
E = empty((aopt, m, n))
|
|
|
|
ssq = []
|
|
|
|
lev = []
|
2006-12-18 12:59:12 +01:00
|
|
|
for ai in range(aopt):
|
2007-07-28 18:05:11 +02:00
|
|
|
E[ai,:,:] = a - dot(T[:,:ai+1], P[:,:ai+1].T)
|
2007-08-24 11:14:24 +02:00
|
|
|
ssq.append([(E[ai,:,:]**2).mean(0), (E[ai,:,:]**2).mean(1)])
|
2007-07-28 18:05:11 +02:00
|
|
|
if scale=='loads':
|
|
|
|
lev.append([((s*T)**2).sum(1), (P**2).sum(1)])
|
|
|
|
else:
|
|
|
|
lev.append([(T**2).sum(1), ((s*P)**2).sum(1)])
|
2006-12-18 12:59:12 +01:00
|
|
|
else:
|
2007-07-28 18:05:11 +02:00
|
|
|
# residuals
|
|
|
|
E = a - dot(T, P.T)
|
|
|
|
SEP = E**2
|
|
|
|
ssq = [SEP.sum(0), SEP.sum(1)]
|
|
|
|
# leverages
|
|
|
|
if scale=='loads':
|
|
|
|
lev = [(1./m)+(T**2).sum(1), (1./n)+((P/s)**2).sum(1)]
|
|
|
|
else:
|
|
|
|
lev = [(1./m)+((T/s)**2).sum(1), (1./n)+(P**2).sum(1)]
|
2007-07-30 11:46:43 +02:00
|
|
|
# variances
|
|
|
|
expvarx = r_[0, 100*e.cumsum()/e.sum()][:aopt+1]
|
|
|
|
|
2007-08-24 11:14:24 +02:00
|
|
|
return {'T':T, 'P':P, 'E':E, 'expvarx':expvarx, 'levx':lev, 'ssqx':ssq, 'aopt':aopt, 'eigvals': e[:aopt,newaxis]}
|
2007-07-28 18:05:11 +02:00
|
|
|
|
|
|
|
def pcr(a, b, aopt, scale='scores',mode='normal',center_axis=0):
|
|
|
|
""" Principal Component Regression.
|
|
|
|
|
|
|
|
Performs PCR on given matrix and returns results in a dictionary.
|
|
|
|
|
|
|
|
:Parameters:
|
|
|
|
a : array
|
|
|
|
Data measurement matrix, (samples x variables)
|
|
|
|
b : array
|
|
|
|
Data response matrix, (samples x responses)
|
|
|
|
aopt : int
|
|
|
|
Number of components to use, aopt<=min(samples, variables)
|
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
:Returns:
|
2007-07-28 18:05:11 +02:00
|
|
|
results : dict
|
|
|
|
keys -- values, T -- scores, P -- loadings, E -- residuals,
|
|
|
|
levx -- leverages, ssqx -- sum of squares, expvarx -- cumulative
|
|
|
|
explained variance, aopt -- number of components used
|
|
|
|
|
|
|
|
:OtherParameters:
|
|
|
|
mode : str
|
|
|
|
Amount of info retained, ('fast', 'normal', 'detailed')
|
|
|
|
center_axis : int
|
|
|
|
Center along given axis. If neg.: no centering (-inf,..., matrix modes)
|
|
|
|
|
|
|
|
:SeeAlso:
|
2007-07-30 11:46:43 +02:00
|
|
|
- pca : other blm
|
2007-07-28 18:05:11 +02:00
|
|
|
- pls : other blm
|
|
|
|
- lpls : other blm
|
|
|
|
|
|
|
|
Notes
|
|
|
|
-----
|
|
|
|
|
|
|
|
Uses kernel speed-up if m>>n or m<<n.
|
|
|
|
|
|
|
|
If residuals turn rank deficient, a lower number of component than given
|
|
|
|
in input will be used. The number of components used is given in results-dict.
|
|
|
|
|
2007-07-28 11:18:48 +02:00
|
|
|
|
2007-07-28 18:05:11 +02:00
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
|
|
|
|
>>> import scipy,engines
|
|
|
|
>>> a=scipy.asarray([[1,2,3],[2,4,5]])
|
2007-07-30 11:46:43 +02:00
|
|
|
>>> b=scipy.asarray([[1,1],[2,3]])
|
|
|
|
>>> dat=engines.pcr(a, 2)
|
|
|
|
>>> dat['expvarx']
|
2007-07-28 18:05:11 +02:00
|
|
|
array([0.,99.8561562, 100.])
|
2007-07-28 11:18:48 +02:00
|
|
|
|
|
|
|
"""
|
2007-07-28 18:05:11 +02:00
|
|
|
k, l = m_shape(b)
|
|
|
|
if center_axis>=0:
|
|
|
|
b = b - expand_dims(b.mean(center_axis), center_axis)
|
|
|
|
dat = pca(a, aopt=aopt, scale=scale, mode=mode, center_axis=center_axis)
|
2007-07-28 11:18:48 +02:00
|
|
|
T = dat['T']
|
2007-07-30 11:46:43 +02:00
|
|
|
weights = apply_along_axis(vnorm, 0, T)**2
|
2007-07-28 11:18:48 +02:00
|
|
|
if scale=='loads':
|
2007-07-30 11:46:43 +02:00
|
|
|
Q = dot(b.T, T*weights)
|
2007-07-28 11:18:48 +02:00
|
|
|
else:
|
2007-07-30 11:46:43 +02:00
|
|
|
Q = dot(b.T, T/weights)
|
2007-07-28 11:18:48 +02:00
|
|
|
|
|
|
|
if mode=='fast':
|
2007-07-28 18:05:11 +02:00
|
|
|
dat.update({'Q':Q})
|
|
|
|
return dat
|
2007-07-28 11:18:48 +02:00
|
|
|
if mode=='detailed':
|
2007-07-28 18:05:11 +02:00
|
|
|
F = empty((aopt, k, l))
|
|
|
|
for i in range(aopt):
|
|
|
|
F[i,:,:] = b - dot(T[:,:i+1], Q[:,:i+1].T)
|
2007-07-28 11:18:48 +02:00
|
|
|
else:
|
|
|
|
F = b - dot(T, Q.T)
|
2007-07-30 11:46:43 +02:00
|
|
|
expvary = r_[0, 100*((T**2).sum(0)*(Q**2).sum(0)/(b**2).sum()).cumsum()[:aopt]]
|
|
|
|
#fixme: Y-var leverages
|
|
|
|
dat.update({'Q':Q, 'F':F, 'expvary':expvary})
|
2007-07-28 11:18:48 +02:00
|
|
|
return dat
|
2007-01-25 12:58:10 +01:00
|
|
|
|
2007-08-07 13:41:03 +02:00
|
|
|
def pls(a, b, aopt=2, scale='scores', mode='normal', center_axis=-1, ab=None):
|
2007-07-28 11:18:48 +02:00
|
|
|
"""Partial Least Squares Regression.
|
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
Performs PLS on given matrix and returns results in a dictionary.
|
|
|
|
|
|
|
|
:Parameters:
|
|
|
|
a : array
|
|
|
|
Data measurement matrix, (samples x variables)
|
|
|
|
b : array
|
|
|
|
Data response matrix, (samples x responses)
|
|
|
|
aopt : int
|
|
|
|
Number of components to use, aopt<=min(samples, variables)
|
|
|
|
|
|
|
|
:Returns:
|
|
|
|
results : dict
|
|
|
|
keys -- values, T -- scores, P -- loadings, E -- residuals,
|
|
|
|
levx -- leverages, ssqx -- sum of squares, expvarx -- cumulative
|
|
|
|
explained variance of descriptors, expvary -- cumulative explained
|
|
|
|
variance of responses, aopt -- number of components used
|
|
|
|
|
|
|
|
:OtherParameters:
|
|
|
|
mode : str
|
|
|
|
Amount of info retained, ('fast', 'normal', 'detailed')
|
|
|
|
center_axis : int
|
|
|
|
Center along given axis. If neg.: no centering (-inf,..., matrix modes)
|
|
|
|
|
|
|
|
:SeeAlso:
|
|
|
|
- pca : other blm
|
|
|
|
- pcr : other blm
|
|
|
|
- lpls : other blm
|
|
|
|
|
|
|
|
Notes
|
|
|
|
-----
|
|
|
|
|
|
|
|
Uses kernel speed-up if m>>n or m<<n.
|
|
|
|
|
|
|
|
If residuals turn rank deficient, a lower number of component than given
|
|
|
|
in input will be used. The number of components used is given in results-dict.
|
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
|
|
|
|
>>> import scipy,engines
|
|
|
|
>>> a=scipy.asarray([[1,2,3],[2,4,5]])
|
|
|
|
>>> b=scipy.asarray([[1,1],[2,3]])
|
|
|
|
>>> dat=engines.pls(a, b, 2)
|
|
|
|
>>> dat['expvarx']
|
|
|
|
array([0.,99.8561562, 100.])
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
"""
|
2007-07-30 11:46:43 +02:00
|
|
|
|
|
|
|
m, n = m_shape(a)
|
2006-12-18 12:59:12 +01:00
|
|
|
if ab!=None:
|
2007-07-30 11:46:43 +02:00
|
|
|
mm, l = m_shape(ab)
|
|
|
|
assert(m==mm)
|
2006-12-18 12:59:12 +01:00
|
|
|
else:
|
2007-07-28 11:18:48 +02:00
|
|
|
k, l = m_shape(b)
|
2007-07-30 20:04:42 +02:00
|
|
|
|
|
|
|
if center_axis>=0:
|
|
|
|
a = a - expand_dims(a.mean(center_axis), center_axis)
|
|
|
|
b = b - expand_dims(b.mean(center_axis), center_axis)
|
2007-07-30 11:46:43 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
W = empty((n, aopt))
|
|
|
|
P = empty((n, aopt))
|
|
|
|
R = empty((n, aopt))
|
|
|
|
Q = empty((l, aopt))
|
|
|
|
T = empty((m, aopt))
|
|
|
|
B = empty((aopt, n, l))
|
2007-07-30 11:46:43 +02:00
|
|
|
|
2007-07-28 11:18:48 +02:00
|
|
|
if ab==None:
|
2006-12-18 12:59:12 +01:00
|
|
|
ab = dot(a.T, b)
|
|
|
|
for i in range(aopt):
|
2007-07-30 20:04:42 +02:00
|
|
|
if ab.shape[1]==1: #pls 1
|
2007-01-31 12:57:59 +01:00
|
|
|
w = ab.reshape(n, l)
|
2007-07-30 11:46:43 +02:00
|
|
|
w = w/vnorm(w)
|
2007-07-30 20:04:42 +02:00
|
|
|
elif n<l: # more yvars than xvars
|
2007-07-30 11:46:43 +02:00
|
|
|
if has_sym:
|
2007-07-30 20:04:42 +02:00
|
|
|
s, u = symeig(dot(ab, ab.T),range=[l,l],overwrite=True)
|
2007-07-30 11:46:43 +02:00
|
|
|
else:
|
|
|
|
u, s, vh = svd(dot(ab, ab.T))
|
|
|
|
w = u[:,0]
|
2007-07-30 20:04:42 +02:00
|
|
|
else: # standard wide xdata
|
2007-07-30 11:46:43 +02:00
|
|
|
if has_sym:
|
2007-07-30 20:04:42 +02:00
|
|
|
s, q = symeig(dot(ab.T, ab),range=[l,l],overwrite=True)
|
2007-07-30 11:46:43 +02:00
|
|
|
else:
|
2007-07-30 20:04:42 +02:00
|
|
|
q, s, vh = svd(dot(ab.T, ab))
|
|
|
|
q = q[:,:1]
|
|
|
|
w = dot(ab, q)
|
|
|
|
w = w/vnorm(w)
|
2006-12-18 12:59:12 +01:00
|
|
|
r = w.copy()
|
2007-07-30 11:46:43 +02:00
|
|
|
if i>0:
|
2007-07-28 11:18:48 +02:00
|
|
|
for j in range(0, i, 1):
|
2006-12-18 12:59:12 +01:00
|
|
|
r = r - dot(P[:,j].T, w)*R[:,j][:,newaxis]
|
2007-08-24 11:14:24 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
t = dot(a, r)
|
2007-07-23 19:33:21 +02:00
|
|
|
tt = vnorm(t)**2
|
2006-12-18 12:59:12 +01:00
|
|
|
p = dot(a.T, t)/tt
|
|
|
|
q = dot(r.T, ab).T/tt
|
|
|
|
ab = ab - dot(p, q.T)*tt
|
|
|
|
T[:,i] = t.ravel()
|
|
|
|
W[:,i] = w.ravel()
|
|
|
|
|
|
|
|
if mode=='fast' and i==aopt-1:
|
|
|
|
if scale=='loads':
|
2007-07-23 19:33:21 +02:00
|
|
|
tnorm = apply_along_axis(vnorm, 0, T)
|
2006-12-18 12:59:12 +01:00
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
return {'T':T, 'W':W}
|
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
P[:,i] = p.ravel()
|
|
|
|
R[:,i] = r.ravel()
|
2006-12-18 12:59:12 +01:00
|
|
|
Q[:,i] = q.ravel()
|
|
|
|
B[i] = dot(R[:,:i+1], Q[:,:i+1].T)
|
2007-07-28 11:18:48 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
if mode=='detailed':
|
|
|
|
E = empty((aopt, m, n))
|
|
|
|
F = empty((aopt, k, l))
|
2007-01-25 12:58:10 +01:00
|
|
|
for i in range(1, aopt+1, 1):
|
|
|
|
E[i-1] = a - dot(T[:,:i], P[:,:i].T)
|
|
|
|
F[i-1] = b - dot(T[:,:i], Q[:,:i].T)
|
2006-12-18 12:59:12 +01:00
|
|
|
else:
|
|
|
|
E = a - dot(T[:,:aopt], P[:,:aopt].T)
|
|
|
|
F = b - dot(T[:,:aopt], Q[:,:aopt].T)
|
|
|
|
|
|
|
|
if scale=='loads':
|
2007-07-23 19:33:21 +02:00
|
|
|
tnorm = apply_along_axis(vnorm, 0, T)
|
2006-12-18 12:59:12 +01:00
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
Q = Q*tnorm
|
|
|
|
P = P*tnorm
|
2007-07-28 11:18:48 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
return {'B':B, 'Q':Q, 'P':P, 'T':T, 'W':W, 'R':R, 'E':E, 'F':F}
|
|
|
|
|
|
|
|
def w_simpls(aat, b, aopt):
|
|
|
|
""" Simpls for wide matrices.
|
|
|
|
Fast pls for crossval, used in calc rmsep for wide X
|
2007-07-28 11:18:48 +02:00
|
|
|
There is no P or W. T is normalised
|
2006-12-18 12:59:12 +01:00
|
|
|
"""
|
|
|
|
bb = b.copy()
|
2007-01-25 12:58:10 +01:00
|
|
|
m, m = aat.shape
|
2007-07-30 11:46:43 +02:00
|
|
|
U = empty((m, aopt)) # W
|
2006-12-18 12:59:12 +01:00
|
|
|
T = empty((m, aopt))
|
2007-07-30 11:46:43 +02:00
|
|
|
H = empty((m, aopt)) # R
|
|
|
|
PROJ = empty((m, aopt)) # P?
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
for i in range(aopt):
|
2007-07-30 11:46:43 +02:00
|
|
|
q, s, vh = svd(dot(dot(b.T, aat), b), full_matrices=0)
|
|
|
|
u = dot(b, q[:,:1]) #y-factor scores
|
2006-12-18 12:59:12 +01:00
|
|
|
U[:,i] = u.ravel()
|
2007-01-25 12:58:10 +01:00
|
|
|
t = dot(aat, u)
|
2007-07-23 19:33:21 +02:00
|
|
|
t = t/vnorm(t)
|
2006-12-18 12:59:12 +01:00
|
|
|
T[:,i] = t.ravel()
|
|
|
|
h = dot(aat, t) #score-weights
|
|
|
|
H[:,i] = h.ravel()
|
|
|
|
PROJ[:,:i+1] = dot(T[:,:i+1], inv(dot(T[:,:i+1].T, H[:,:i+1])) )
|
|
|
|
if i<aopt:
|
|
|
|
b = b - dot(PROJ[:,:i+1], dot(H[:,:i+1].T,b) )
|
|
|
|
C = dot(bb.T, T)
|
|
|
|
|
2007-01-25 12:58:10 +01:00
|
|
|
return {'T':T, 'U':U, 'Q':C, 'H':H}
|
2006-12-18 12:59:12 +01:00
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
def w_pls(aat, b, aopt):
|
|
|
|
""" Pls for wide matrices.
|
|
|
|
Fast pls for crossval, used in calc rmsep for wide X
|
|
|
|
There is no P or W. T is normalised
|
2007-07-30 20:04:42 +02:00
|
|
|
|
|
|
|
aat = centered kernel matrix
|
|
|
|
b = centered y
|
2007-07-30 11:46:43 +02:00
|
|
|
"""
|
|
|
|
bb = b.copy()
|
2007-07-30 20:04:42 +02:00
|
|
|
k, l = m_shape(b)
|
|
|
|
m, m = m_shape(aat)
|
2007-07-30 11:46:43 +02:00
|
|
|
U = empty((m, aopt)) # W
|
|
|
|
T = empty((m, aopt))
|
|
|
|
R = empty((m, aopt)) # R
|
|
|
|
PROJ = empty((m, aopt)) # P?
|
|
|
|
|
|
|
|
for i in range(aopt):
|
|
|
|
if has_sym:
|
2007-07-30 20:04:42 +02:00
|
|
|
s, q = symeig(dot(dot(b.T, aat), b), range=(l,l),overwrite=True)
|
2007-07-30 11:46:43 +02:00
|
|
|
else:
|
|
|
|
q, s, vh = svd(dot(dot(b.T, aat), b), full_matrices=0)
|
|
|
|
q = q[:,:1]
|
|
|
|
u = dot(b , q) #y-factor scores
|
|
|
|
U[:,i] = u.ravel()
|
|
|
|
t = dot(aat, u)
|
2007-07-30 20:04:42 +02:00
|
|
|
|
2007-07-30 11:46:43 +02:00
|
|
|
t = t/vnorm(t)
|
|
|
|
T[:,i] = t.ravel()
|
2007-07-30 20:04:42 +02:00
|
|
|
r = dot(aat, t)#score-weights
|
|
|
|
#r = r/vnorm(r)
|
2007-07-30 11:46:43 +02:00
|
|
|
R[:,i] = r.ravel()
|
|
|
|
PROJ[:,: i+1] = dot(T[:,:i+1], inv(dot(T[:,:i+1].T, R[:,:i+1])) )
|
|
|
|
if i<aopt:
|
2007-07-30 20:04:42 +02:00
|
|
|
b = b - dot(PROJ[:,:i+1], dot(R[:,:i+1].T, b) )
|
2007-07-30 11:46:43 +02:00
|
|
|
C = dot(bb.T, T)
|
|
|
|
|
2007-07-30 20:04:42 +02:00
|
|
|
return {'T':T, 'U':U, 'Q':C, 'R':R}
|
2007-07-30 11:46:43 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
def bridge(a, b, aopt, scale='scores', mode='normal', r=0):
|
|
|
|
"""Undeflated Ridged svd(X'Y)
|
|
|
|
"""
|
2007-07-28 11:18:48 +02:00
|
|
|
m, n = m_shape(a)
|
2007-01-25 12:58:10 +01:00
|
|
|
k, l = m_shape(b)
|
|
|
|
u, s, vt = svd(b, full_matrices=0)
|
2006-12-18 12:59:12 +01:00
|
|
|
g0 = dot(u*s, u.T)
|
|
|
|
g = (1 - r)*g0 + r*eye(m)
|
|
|
|
ag = dot(a.T, g)
|
2007-01-25 12:58:10 +01:00
|
|
|
u, s, vt = svd(ag, full_matrices=0)
|
2006-12-18 12:59:12 +01:00
|
|
|
W = u[:,:aopt]
|
|
|
|
K = vt[:aopt,:].T
|
|
|
|
T = dot(a, W)
|
2007-07-23 19:33:21 +02:00
|
|
|
tnorm = apply_along_axis(vnorm, 0, T) # norm of T-columns
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
if mode == 'fast':
|
|
|
|
if scale=='loads':
|
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
return {'T':T, 'W':W}
|
|
|
|
|
|
|
|
U = dot(g0, K) #fixme check this
|
2007-01-25 12:58:10 +01:00
|
|
|
Q = dot(b.T, dot(T, inv(dot(T.T, T)) ))
|
|
|
|
B = zeros((aopt, n, l), dtype='f')
|
2006-12-18 12:59:12 +01:00
|
|
|
for i in range(aopt):
|
|
|
|
B[i] = dot(W[:,:i+1], Q[:,:i+1].T)
|
2007-07-28 11:18:48 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
if mode == 'detailed':
|
|
|
|
E = empty((aopt, m, n))
|
|
|
|
F = empty((aopt, k, l))
|
|
|
|
for i in range(aopt):
|
|
|
|
E[i] = a - dot(T[:,:i+1], W[:,:i+1].T)
|
|
|
|
F[i] = b - dot(a, B[i])
|
|
|
|
else: #normal
|
|
|
|
F = b - dot(a, B[-1])
|
|
|
|
E = a - dot(T, W.T)
|
2007-07-28 11:18:48 +02:00
|
|
|
# leverages
|
|
|
|
# fixme: probably need an orthogonal basis for row-space leverage
|
|
|
|
# T (scores) are not orthogonal
|
|
|
|
# Using a qr decomp to get an orthonormal basis for row-space
|
|
|
|
#Tq = qr(T)[0]
|
|
|
|
#s_lev,v_lev = leverage(aopt,Tq,W)
|
|
|
|
# explained variance
|
|
|
|
#var_x, exp_var_x = variances(a,T,W)
|
|
|
|
#qnorm = apply_along_axis(norm, 0, Q)
|
|
|
|
#var_y, exp_var_y = variances(b,U,Q/qnorm)
|
2006-12-18 12:59:12 +01:00
|
|
|
|
|
|
|
if scale=='loads':
|
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
Q = Q*tnorm
|
2007-07-28 11:18:48 +02:00
|
|
|
|
2006-12-18 12:59:12 +01:00
|
|
|
return {'B':B, 'W':W, 'T':T, 'Q':Q, 'E':E, 'F':F, 'U':U, 'P':W}
|
2007-01-25 12:58:10 +01:00
|
|
|
|
2007-07-23 19:33:21 +02:00
|
|
|
|
2007-07-23 20:07:10 +02:00
|
|
|
def nipals_lpls(X, Y, Z, a_max, alpha=.7, mean_ctr=[2, 0, 1], mode='normal', scale='scores', verbose=False):
|
2007-07-23 19:33:21 +02:00
|
|
|
""" L-shaped Partial Least Sqaures Regression by the nipals algorithm.
|
|
|
|
|
|
|
|
(X!Z)->Y
|
|
|
|
:input:
|
|
|
|
X : data matrix (m, n)
|
|
|
|
Y : data matrix (m, l)
|
|
|
|
Z : data matrix (n, o)
|
|
|
|
|
|
|
|
:output:
|
|
|
|
T : X-scores
|
|
|
|
W : X-weights/Z-weights
|
|
|
|
P : X-loadings
|
|
|
|
Q : Y-loadings
|
|
|
|
U : X-Y relation
|
|
|
|
L : Z-scores
|
|
|
|
K : Z-loads
|
|
|
|
B : Regression coefficients X->Y
|
|
|
|
b0: Regression coefficient intercept
|
|
|
|
evx : X-explained variance
|
|
|
|
evy : Y-explained variance
|
|
|
|
evz : Z-explained variance
|
|
|
|
|
|
|
|
:Notes:
|
|
|
|
|
|
|
|
"""
|
|
|
|
if mean_ctr!=None:
|
|
|
|
xctr, yctr, zctr = mean_ctr
|
|
|
|
X, mnX = center(X, xctr)
|
|
|
|
Y, mnY = center(Y, xctr)
|
|
|
|
Z, mnZ = center(Z, zctr)
|
|
|
|
|
|
|
|
varX = pow(X, 2).sum()
|
|
|
|
varY = pow(Y, 2).sum()
|
|
|
|
varZ = pow(Z, 2).sum()
|
|
|
|
|
|
|
|
m, n = X.shape
|
|
|
|
k, l = Y.shape
|
|
|
|
u, o = Z.shape
|
|
|
|
|
|
|
|
# initialize
|
2007-07-23 20:07:10 +02:00
|
|
|
U = empty((k, a_max))
|
|
|
|
Q = empty((l, a_max))
|
|
|
|
T = empty((m, a_max))
|
|
|
|
W = empty((n, a_max))
|
|
|
|
P = empty((n, a_max))
|
|
|
|
K = empty((o, a_max))
|
|
|
|
L = empty((u, a_max))
|
2007-07-30 20:04:42 +02:00
|
|
|
B = empty((a_max, n, l))
|
|
|
|
b0 = empty((a_max, m, l))
|
2007-07-23 20:07:10 +02:00
|
|
|
var_x = empty((a_max,))
|
|
|
|
var_y = empty((a_max,))
|
|
|
|
var_z = empty((a_max,))
|
2007-07-23 19:33:21 +02:00
|
|
|
|
2007-07-23 20:07:10 +02:00
|
|
|
for a in range(a_max):
|
2007-07-23 19:33:21 +02:00
|
|
|
if verbose:
|
|
|
|
print "\n Working on comp. %s" %a
|
|
|
|
u = Y[:,:1]
|
|
|
|
diff = 1
|
2007-07-30 20:04:42 +02:00
|
|
|
MAX_ITER = 200
|
|
|
|
lim = 1e-16
|
2007-07-23 19:33:21 +02:00
|
|
|
niter = 0
|
|
|
|
while (diff>lim and niter<MAX_ITER):
|
|
|
|
niter += 1
|
|
|
|
u1 = u.copy()
|
|
|
|
w = dot(X.T, u)
|
|
|
|
w = w/sqrt(dot(w.T, w))
|
|
|
|
l = dot(Z, w)
|
|
|
|
k = dot(Z.T, l)
|
|
|
|
k = k/sqrt(dot(k.T, k))
|
|
|
|
w = alpha*k + (1-alpha)*w
|
|
|
|
w = w/sqrt(dot(w.T, w))
|
|
|
|
t = dot(X, w)
|
|
|
|
c = dot(Y.T, t)
|
|
|
|
c = c/sqrt(dot(c.T, c))
|
|
|
|
u = dot(Y, c)
|
|
|
|
diff = abs(u1 - u).max()
|
|
|
|
if verbose:
|
|
|
|
print "Converged after %s iterations" %niter
|
|
|
|
tt = dot(t.T, t)
|
|
|
|
p = dot(X.T, t)/tt
|
|
|
|
q = dot(Y.T, t)/tt
|
|
|
|
l = dot(Z, w)
|
|
|
|
|
|
|
|
U[:,a] = u.ravel()
|
|
|
|
W[:,a] = w.ravel()
|
|
|
|
P[:,a] = p.ravel()
|
|
|
|
T[:,a] = t.ravel()
|
|
|
|
Q[:,a] = q.ravel()
|
|
|
|
L[:,a] = l.ravel()
|
|
|
|
K[:,a] = k.ravel()
|
|
|
|
|
|
|
|
X = X - dot(t, p.T)
|
|
|
|
Y = Y - dot(t, q.T)
|
|
|
|
Z = (Z.T - dot(w, l.T)).T
|
|
|
|
|
|
|
|
var_x[a] = pow(X, 2).sum()
|
|
|
|
var_y[a] = pow(Y, 2).sum()
|
|
|
|
var_z[a] = pow(Z, 2).sum()
|
|
|
|
|
2007-07-30 20:04:42 +02:00
|
|
|
B[a] = dot(dot(W[:,:a+1], inv(dot(P[:,:a+1].T, W[:,:a+1]))), Q[:,:a+1].T)
|
|
|
|
b0[a] = mnY - dot(mnX, B[a])
|
2007-07-23 19:33:21 +02:00
|
|
|
|
|
|
|
# variance explained
|
|
|
|
evx = 100.0*(1 - var_x/varX)
|
|
|
|
evy = 100.0*(1 - var_y/varY)
|
|
|
|
evz = 100.0*(1 - var_z/varZ)
|
|
|
|
if scale=='loads':
|
|
|
|
tnorm = apply_along_axis(vnorm, 0, T)
|
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
Q = Q*tnorm
|
|
|
|
knorm = apply_along_axis(vnorm, 0, K)
|
|
|
|
L = L*knorm
|
|
|
|
K = K/knorm
|
|
|
|
|
|
|
|
return {'T':T, 'W':W, 'P':P, 'Q':Q, 'U':U, 'L':L, 'K':K, 'B':B, 'b0':b0, 'evx':evx, 'evy':evy, 'evz':evz}
|
|
|
|
|
|
|
|
|
|
|
|
|
2007-07-30 20:04:42 +02:00
|
|
|
def nipals_pls(X, Y, a_max, alpha=.7, ax_center=0, mode='normal', scale='scores', verbose=False):
|
|
|
|
"""Partial Least Sqaures Regression by the nipals algorithm.
|
|
|
|
|
|
|
|
(X!Z)->Y
|
|
|
|
:input:
|
|
|
|
X : data matrix (m, n)
|
|
|
|
Y : data matrix (m, l)
|
|
|
|
|
|
|
|
:output:
|
|
|
|
T : X-scores
|
|
|
|
W : X-weights/Z-weights
|
|
|
|
P : X-loadings
|
|
|
|
Q : Y-loadings
|
|
|
|
U : X-Y relation
|
|
|
|
B : Regression coefficients X->Y
|
|
|
|
b0: Regression coefficient intercept
|
|
|
|
evx : X-explained variance
|
|
|
|
evy : Y-explained variance
|
|
|
|
evz : Z-explained variance
|
|
|
|
|
|
|
|
:Notes:
|
|
|
|
|
|
|
|
"""
|
|
|
|
if ax_center>=0:
|
|
|
|
mn_x = expand_dims(X.mean(ax_center), ax_center)
|
|
|
|
mn_y = expand_dims(Y.mean(ax_center), ax_center)
|
|
|
|
X = X - mn_x
|
|
|
|
Y = Y - mn_y
|
|
|
|
|
|
|
|
varX = pow(X, 2).sum()
|
|
|
|
varY = pow(Y, 2).sum()
|
|
|
|
|
|
|
|
m, n = X.shape
|
|
|
|
k, l = Y.shape
|
|
|
|
|
|
|
|
# initialize
|
|
|
|
U = empty((k, a_max))
|
|
|
|
Q = empty((l, a_max))
|
|
|
|
T = empty((m, a_max))
|
|
|
|
W = empty((n, a_max))
|
|
|
|
P = empty((n, a_max))
|
|
|
|
B = empty((a_max, n, l))
|
|
|
|
b0 = empty((a_max, m, l))
|
|
|
|
var_x = empty((a_max,))
|
|
|
|
var_y = empty((a_max,))
|
|
|
|
|
|
|
|
t1 = X[:,:1]
|
|
|
|
for a in range(a_max):
|
|
|
|
if verbose:
|
|
|
|
print "\n Working on comp. %s" %a
|
|
|
|
u = Y[:,:1]
|
|
|
|
diff = 1
|
|
|
|
MAX_ITER = 100
|
|
|
|
lim = 1e-16
|
|
|
|
niter = 0
|
|
|
|
while (diff>lim and niter<MAX_ITER):
|
|
|
|
niter += 1
|
|
|
|
#u1 = u.copy()
|
|
|
|
w = dot(X.T, u)
|
|
|
|
w = w/sqrt(dot(w.T, w))
|
|
|
|
#l = dot(Z, w)
|
|
|
|
#k = dot(Z.T, l)
|
|
|
|
#k = k/sqrt(dot(k.T, k))
|
|
|
|
#w = alpha*k + (1-alpha)*w
|
|
|
|
#w = w/sqrt(dot(w.T, w))
|
|
|
|
t = dot(X, w)
|
|
|
|
q = dot(Y.T, t)
|
|
|
|
q = q/sqrt(dot(q.T, q))
|
|
|
|
u = dot(Y, q)
|
|
|
|
diff = vnorm(t1 - t)
|
|
|
|
t1 = t.copy()
|
|
|
|
if verbose:
|
|
|
|
print "Converged after %s iterations" %niter
|
|
|
|
#tt = dot(t.T, t)
|
|
|
|
#p = dot(X.T, t)/tt
|
|
|
|
#q = dot(Y.T, t)/tt
|
|
|
|
#l = dot(Z, w)
|
|
|
|
p = dot(X.T, t)/dot(t.T, t)
|
|
|
|
p_norm = vnorm(p)
|
|
|
|
t = t*p_norm
|
|
|
|
w = w*p_norm
|
|
|
|
p = p/p_norm
|
|
|
|
|
|
|
|
U[:,a] = u.ravel()
|
|
|
|
W[:,a] = w.ravel()
|
|
|
|
P[:,a] = p.ravel()
|
|
|
|
T[:,a] = t.ravel()
|
|
|
|
Q[:,a] = q.ravel()
|
|
|
|
|
|
|
|
X = X - dot(t, p.T)
|
|
|
|
Y = Y - dot(t, q.T)
|
|
|
|
|
|
|
|
var_x[a] = pow(X, 2).sum()
|
|
|
|
var_y[a] = pow(Y, 2).sum()
|
|
|
|
|
|
|
|
B[a] = dot(dot(W[:,:a+1], inv(dot(P[:,:a+1].T, W[:,:a+1]))), Q[:,:a+1].T)
|
|
|
|
b0[a] = mn_y - dot(mn_x, B[a])
|
|
|
|
|
|
|
|
# variance explained
|
|
|
|
evx = 100.0*(1 - var_x/varX)
|
|
|
|
evy = 100.0*(1 - var_y/varY)
|
|
|
|
|
|
|
|
if scale=='loads':
|
|
|
|
tnorm = apply_along_axis(vnorm, 0, T)
|
|
|
|
T = T/tnorm
|
|
|
|
W = W*tnorm
|
|
|
|
Q = Q*tnorm
|
|
|
|
|
|
|
|
return {'T':T, 'W':W, 'P':P, 'Q':Q, 'U':U, 'B':B, 'b0':b0, 'evx':evx, 'evy':evy}
|
|
|
|
|
2007-07-23 19:33:21 +02:00
|
|
|
|
|
|
|
########### Helper routines #########
|
|
|
|
|
2007-01-25 12:58:10 +01:00
|
|
|
def m_shape(array):
|
|
|
|
return matrix(array).shape
|
2007-01-25 13:36:32 +01:00
|
|
|
|
2007-07-28 18:05:11 +02:00
|
|
|
def esvd(data, amax=None):
|
2007-01-25 13:36:32 +01:00
|
|
|
"""SVD with the option of economy sized calculation
|
|
|
|
Calculate subspaces of X'X or XX' depending on the shape
|
|
|
|
of the matrix.
|
|
|
|
|
|
|
|
Good for extreme fat or thin matrices
|
|
|
|
|
2007-07-26 20:32:48 +02:00
|
|
|
:notes:
|
2007-01-25 13:36:32 +01:00
|
|
|
Numpy supports this by setting full_matrices=0
|
|
|
|
"""
|
|
|
|
m, n = data.shape
|
|
|
|
if m>=n:
|
2007-07-26 20:32:48 +02:00
|
|
|
kernel = dot(data.T, data)
|
2007-07-28 18:05:11 +02:00
|
|
|
if has_sym:
|
2007-08-07 13:41:03 +02:00
|
|
|
if amax==None:
|
|
|
|
amax = n
|
|
|
|
pcrange = None
|
|
|
|
else:
|
|
|
|
pcrange = [n-amax, n]
|
2007-07-28 18:05:11 +02:00
|
|
|
s, v = symeig(kernel, range=pcrange, overwrite=True)
|
2007-08-24 11:14:24 +02:00
|
|
|
s = s[::-1].real
|
|
|
|
v = v[:,::-1].real
|
2007-07-28 18:05:11 +02:00
|
|
|
else:
|
|
|
|
u, s, vt = svd(kernel)
|
|
|
|
v = vt.T
|
2007-08-07 13:41:03 +02:00
|
|
|
s = sqrt(s)
|
|
|
|
u = dot(data, v)/s
|
2007-01-25 13:36:32 +01:00
|
|
|
else:
|
2007-07-26 20:32:48 +02:00
|
|
|
kernel = dot(data, data.T)
|
2007-07-28 18:05:11 +02:00
|
|
|
if has_sym:
|
2007-08-07 13:41:03 +02:00
|
|
|
if amax==None:
|
|
|
|
amax = m
|
|
|
|
pcrange = None
|
|
|
|
else:
|
|
|
|
pcrange = [m-amax, m]
|
2007-07-28 18:05:11 +02:00
|
|
|
s, u = symeig(kernel, range=pcrange, overwrite=True)
|
2007-08-07 13:41:03 +02:00
|
|
|
s = s[::-1]
|
|
|
|
u = u[:,::-1]
|
2007-07-28 18:05:11 +02:00
|
|
|
else:
|
|
|
|
u, s, vt = svd(kernel)
|
2007-08-07 13:41:03 +02:00
|
|
|
s = sqrt(s)
|
|
|
|
v = dot(data.T, u)/s
|
2007-08-24 11:14:24 +02:00
|
|
|
# some use of symeig returns the 0 imaginary part
|
|
|
|
return u.real, s.real, v.real
|
2007-07-23 19:33:21 +02:00
|
|
|
|
|
|
|
def vnorm(x):
|
|
|
|
# assume column arrays (or vectors)
|
|
|
|
return math.sqrt(dot(x.T, x))
|
|
|
|
|
|
|
|
def center(a, axis):
|
|
|
|
# 0 = col center, 1 = row center, 2 = double center
|
|
|
|
# -1 = nothing
|
|
|
|
if axis==-1:
|
|
|
|
mn = zeros((a.shape[1],))
|
|
|
|
elif axis==0:
|
|
|
|
mn = a.mean(0)
|
|
|
|
elif axis==1:
|
|
|
|
mn = a.mean(1)[:,newaxis]
|
|
|
|
elif axis==2:
|
|
|
|
mn = a.mean(0) + a.mean(1)[:,newaxis] - a.mean()
|
|
|
|
else:
|
|
|
|
raise IOError("input error: axis must be in [-1,0,1,2]")
|
|
|
|
|
|
|
|
return a - mn, mn
|
2007-08-07 13:41:03 +02:00
|
|
|
|
|
|
|
def scale(a, axis):
|
|
|
|
if axis==-1:
|
|
|
|
sc = zeros((a.shape[1],))
|
|
|
|
elif axis==0:
|
|
|
|
sc = a.std(0)
|
|
|
|
elif axis==1:
|
|
|
|
sc = a.std(1)[:,newaxis]
|
|
|
|
else:
|
|
|
|
raise IOError("input error: axis must be in [-1,0,1]")
|
|
|
|
|
|
|
|
return a - sc, sc
|
|
|
|
|