-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdatatools.py
More file actions
231 lines (175 loc) · 6.12 KB
/
datatools.py
File metadata and controls
231 lines (175 loc) · 6.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""A set of simple tools used to process data.
Implemented tools:
- PCA, principle component analysis
Yujia Li, 07/2013
"""
import numpy as np
import scipy.linalg as la
_SMALL_CONSTANT = 1e-8
def pca(x, K):
"""(x, K) --> (xnew, basis, xmean)
x: N*D is the data matrix, each row is a data vector
K: an integer, the dimensionality of the low dimensional space to project
xnew: N*K projected data matrix
basis: D*K matrix, each column is a basis vector for the low dimensional space
xmean: 1-D vector, the mean vector of x
"""
xmean = x.mean(axis=0)
X = x - xmean
[w, basis] = np.linalg.eigh(X.T.dot(X))
idx = np.argsort(w)
idx = idx[::-1]
basis = basis[:,idx[:K]]
xnew = X.dot(basis)
return xnew, basis, xmean
def pca_dim_reduction(x, basis, xmean=None):
"""(x, basis, xmean) --> xnew
Dimensionality reduction with PCA.
x: N*D data matrix
basis: D*K basis matrix
xmean: 1-D vector, mean vector used in PCA, if not set, use the mean of x instead
xnew: N*K new data matrix
"""
if xmean == None:
xmean = x.mean(axis=0)
xnew = (x - xmean).dot(basis)
return xnew
def zero_mean_normalize(x, xmean=None, std=None):
"""(x, xmean=None, std=None) --> xnew
Subtract mean from x, then divide by standard deviation, so that each
dimension is roughly normally distributed.
x: N*D data matrix
xmean: D-dimensional vector, mean of each dimension
std: D-dimensional vector, std of each dimension
xnew: normalized N*D data matrix
"""
if xmean == None:
xmean = x.mean(axis=0)
if std == None:
std = x.std(axis=0) + _SMALL_CONSTANT
return (x - xmean) / std
def scale_normalization(x, std=None):
"""(x, std=None) --> xnew
Devide each dimension of x by the standard deviation of that dimension so
that all dimensions have roughly the same scale.
x: N*D data matrix
std: D-dimensional vector. It will be used as standard deviation if given.
xnew: normalized N*D data matrix
"""
if std == None:
std = x.std(axis=0) + _SMALL_CONSTANT
return x / std
def list_to_mat(xlist):
"""(xlist) --> x
Concatenate a list of matrices into a full matrix. All matrices in the list
should have the same width, i.e. of size N*K where K is the same for all
matrices.
The size of x will be (sum_i N_i) * K.
"""
assert (len(xlist) > 0)
N, K = xlist[0].shape
for i in range(1, len(xlist)):
N += xlist[i].shape[0]
x = np.empty((N,K), xlist[0].dtype)
i_start = 0
for i in range(len(xlist)):
x[i_start:i_start + xlist[i].shape[0]] = xlist[i]
i_start += xlist[i].shape[0]
return x
def list_to_vec(xlist):
"""(xlist) --> x
Concatenate a list of vectors into a long vector. All vectors are 1-d
numpy ndarrays of the same type.
"""
assert (len(xlist) > 0)
total_len = sum([v.size for v in xlist])
x = np.empty(total_len, dtype=xlist[0].dtype)
i_start = 0
for i in range(len(xlist)):
x[i_start:i_start + xlist[i].size] = xlist[i]
i_start += xlist[i].size
return x
def list_mode(x, K):
"""Find the mode (mose frequent element) in x. x can be indexed by one
integer, i.e. a list or 1-d array. Each element in x is restricted to be
in range 0 to K-1."""
count = np.zeros(K, dtype=np.int)
for i in xrange(len(x)):
count[x[i]] += 1
return count.argmax()
def switch_row_column_major(x, mat_size):
"""(x, mat_size) --> new_x
Switch the data ordering of matrices between row major and column major.
x: N*D matrix, each row stores a matrix in row major or column major order.
mat_size: the original shape of the matrices stored in x
new_x: same size as x, but with row major switched to column major or the
other way around.
"""
new_x = x.copy()
for i in range(x.shape[0]):
new_x[i] = x[i].reshape(mat_size).T.reshape([1, x.shape[1]])
return new_x
class Preprocessor(object):
"""Base class for preprocessors."""
def __init__(self, x=None, prev=None, **kwargs):
"""Construct preprocessor. Can use some data x, or chained with
another preprocessor."""
pass
def process(self, x):
"""Process data x and return a processed copy x_new."""
pass
class BlankPreprocessor(Preprocessor):
"""Do nothing."""
def __init__(self):
pass
def process(self, x):
return x
class MeanStdPreprocessor(Preprocessor):
"""Subtract mean and normalize by standard deviation preprocessor."""
def __init__(self, x, prev=None):
self.prev = prev
if prev:
x = prev.process(x)
self.avg = x.mean(axis=0)
self.std = x.std(axis=0) + _SMALL_CONSTANT
def process(self, x):
if self.prev:
x = self.prev.process(x)
return (x - self.avg) / self.std
class StdNormPreprocessor(Preprocessor):
"""Normalize the features using standard deviation."""
def __init__(self, x, prev=None):
self.prev = prev
if prev:
x = prev.process(x)
self.std = x.std(axis=0) + _SMALL_CONSTANT
def process(self, x):
if self.prev:
x = self.prev.process(x)
return x / self.std
class WhiteningPreprocessor(Preprocessor):
"""Whitening - decorrelate covariance."""
def __init__(self, x, prev=None):
self.prev = prev
if prev:
x = prev.process(x)
self.avg = x.mean(axis=0)
cov = x.T.dot(x) / x.shape[0]
self.m = la.inv(la.sqrtm(cov).real + np.eye(x.shape[1]) * _SMALL_CONSTANT)
def process(self, x):
if self.prev:
x = self.prev.process(x)
return (x - self.avg).dot(self.m)
class PCAPreprocessor(Preprocessor):
"""PCA"""
def __init__(self, x, prev=None, K=None):
self.prev = prev
if prev:
x = prev.process(x)
if K == None:
K = x.shape[1] / 2 + 1
_, self.basis, self.avg = pca(x, K)
def process(self, x):
if self.prev:
x = self.prev.process(x)
return pca_dim_reduction(x, self.basis, self.avg)