/
dimensionality_reduction.py
237 lines (191 loc) · 6.35 KB
/
dimensionality_reduction.py
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
229
230
231
232
233
234
235
236
237
'''
Author: Sebastian Alfers
This file is part of my thesis 'Evaluation and implementation of cluster-based dimensionality reduction'
License: https://github.com/sebastian-alfers/master-thesis/blob/master/LICENSE
'''
from sklearn.feature_extraction import FeatureHasher
from sklearn.decomposition import PCA, IncrementalPCA, NMF, TruncatedSVD, KernelPCA
import time
from sklearn import random_projection, manifold
import numpy as np
from copy import copy
def noDR(data, labels, new_dimension):
if hasattr(data, "toarray"):
data = data.toarray()
return (data, 0.0)
def hash(data, labels, new_dimension):
print "start hashing trick..."
# convert features as dict
dictList = list()
if hasattr(data, "indices"):
#ind = data.indices
#dat = data.data
data = data.toarray()
indices = range(len(data[0]))
for item in data:
zipped = zip(indices, item)
row = dict()
for index,value in zipped:
if value != 0:
row[str(index)] = value
dictList.append(row)
a = 234
else:
indices = map(str, range(len(data[0])))
for row in data:
dictList.append(dict(zip(indices, row)))
start = time.time()
hasher = FeatureHasher(n_features=new_dimension) # , input_type='dict'
reduced = hasher.fit_transform(dictList).toarray()
end = time.time()
return (reduced, end-start)
def randomProjection(data, labels, new_dimension):
print ("start random projection...")
start = time.time()
transformer = random_projection.GaussianRandomProjection(n_components=new_dimension)
reduced = transformer.fit_transform(data)
end = time.time()
#print (" took %f" % (end - start))
return (reduced, end-start)
def sparseRandomProjection(data, label, new_dimension):
print ("start sparse random projection...")
start = time.time()
transformer = random_projection.SparseRandomProjection(n_components=new_dimension)
reduced = transformer.fit_transform(data)
end = time.time()
#print (" took %f" % (end - start))
return (reduced, end-start)
def pca(data, labels, new_dimension):
print "start pca..."
if hasattr(data, "toarray"):
data = data.toarray()
start = time.time()
pca = PCA(n_components=new_dimension)
reduced = pca.fit_transform(data)
end = time.time()
return (reduced, end-start)
def ipca(data, labels, new_dimension):
print "start incremental pca..."
if hasattr(data, "todense"):
data = np.array(data.todense())
start = time.time()
pca = IncrementalPCA(n_components=new_dimension)
reduced = pca.fit_transform(data)
end = time.time()
return (reduced, end-start)
def kernelPCA(data, labels, new_dimension):
print "start kernel pca..."
if hasattr(data, "toarray"):
data = data.toarray()
start = time.time()
pca = KernelPCA(fit_inverse_transform=True, gamma=10, n_components=new_dimension, alpha=2)
reduced = pca.fit_transform(data)
end = time.time()
return (reduced, end-start)
def truncatedSVD(data, labels, new_dimension):
print "start truncatedSVD..."
start = time.time()
pca = TruncatedSVD(n_components=new_dimension)
reduced = pca.fit_transform(data)
end = time.time()
return (reduced, end-start)
def nnMatrixFactorisation(data, labels, new_dimension):
print "non negative matrix factorisation..."
start = time.time()
mf = NMF(n_components=new_dimension)
reduced = mf.fit_transform(data)
end = time.time()
return (reduced, end-start)
def tsne(data, labels, new_dimension):
print "tsne..."
#if hasattr(data, "toarray"):
# data = data.toarray()
start = time.time()
tsne = manifold.TSNE(n_components=new_dimension, learning_rate=500)
reduced = tsne.fit_transform(data)
end = time.time()
return (reduced, end-start)
def isomap(data, labels, new_dimension):
print "isomap..."
if hasattr(data, "toarray"):
data = data.toarray()
start = time.time()
iso = manifold.Isomap(n_components=new_dimension)
reduced = iso.fit_transform(data)
end = time.time()
return (reduced, end-start)
def mds(data, labels, new_dimension):
print "mds ..."
if hasattr(data, "toarray"):
data = data.toarray()
start = time.time()
mds = manifold.MDS(n_components=new_dimension)
reduced = mds.fit_transform(data)
end = time.time()
return (reduced, end-start)
def lle(data, labels, new_dimension):
print "lle..."
if hasattr(data, "toarray"):
data = data.toarray()
start = time.time()
lle = manifold.LocallyLinearEmbedding(n_components=new_dimension) # n_neighbors= int(new_dimension/2),
reduced = lle.fit_transform(data)
end = time.time()
return (reduced, end-start)
def spectralEmbedding(data, labels, new_dimension):
print "spectralEmbedding..."
start = time.time()
mds = manifold.SpectralEmbedding(n_components=new_dimension)
reduced = mds.fit_transform(data)
end = time.time()
return (reduced, end-start)
options = {
'no_DR': noDR,
'hash': hash,
'rp': randomProjection,
'srp': sparseRandomProjection,
'pca': pca,
'incremental_pca': ipca,
'kernel_pca': kernelPCA,
'truncated_svd': truncatedSVD,
'matrix_factorisaton': nnMatrixFactorisation,
'tsne': tsne,
'isomap': isomap,
'mds': mds,
'lle': lle,
'spectralEmbedding': spectralEmbedding
}
def getFewAlgos():
options = {
'hash': hash,
'rp': randomProjection,
'lle': lle
}
return options
def getAllFastAlgos():
fastOptions = getAllAlgos()
del(fastOptions["matrix_factorisaton"])
del(fastOptions["tsne"])
del(fastOptions["mds"])
return fastOptions
def getFasterAlgos():
fasterOptions = getAllAlgos()
del(fasterOptions["isomap"])
del(fasterOptions["lle"])
del(fasterOptions["kernel_pca"])
return fasterOptions
def getAllAlgos():
return copy(options)
def getAllAlgosInclude(include):
allAlgos = getAllAlgos()
includedAlgos = dict()
for key in include:
includedAlgos[key] = allAlgos[key]
return includedAlgos
def getAllAlgosExlude(exclude):
allAlgos = getAllAlgos()
for item in exclude:
del(allAlgos[item])
return allAlgos
def reduceByKey(key, d, l, dimensionValue):
return options[key](d,l, dimensionValue)