-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelm.py
253 lines (213 loc) · 7.52 KB
/
elm.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
# TODO
# 1. 实现高斯核函数
# 2. 对比高斯核函数、随机矩阵下SVM和ELM的分类效果、速度
# 3. 实现多层ELM
class ELM:
"""
An ELM wrapper
"""
def __init__(self, args) -> None:
if args.type == 'basic':
self.elm = basic_ELM(args.input_shape,
args.hidden_dim,
args.activation)
elif args.type == 'normal':
self.elm = normal_ELM(args.input_shape,
args.output_shape,
args.activation,
args.normalize)
elif args.type == 'classic':
self.elm = classic_ELM(args.input_shape,
args.hidden_dim,
args.activation,
args.normalize,
args.classes)
def train(self, x, y):
self.elm.train(x, y)
def test(self, x, y):
self.elm.test(x, y)
def infer(self, x, y):
self.elm.infer(x, y)
class basic_ELM:
def __init__(self, input_shape, hidden_dim, act='sigmoid') -> None:
"""basic ELM for two class classify
Args:
input_shape (int): number of input features
hidden_dim (int): number of hidden layer
act (str, optional): activite function. Defaults to 'sigmoid'.
"""
self.w = np.random.rand(input_shape, hidden_dim)
self.b = np.random.rand(hidden_dim)
self.beta = np.random.rand(hidden_dim, 1)
self.act = self.act_func(act)
def train(self, x, y):
"""train basic elm
Args:
x (numpy.ndarray): (bsz, hidden_dim) train examples
y (numpy.ndarray): (bsz, ) labels
"""
assert x.shape[1] == self.w.shape[0]
x = np.matmul(x, self.w) + self.b
x = self.act(x)
self.beta = np.matmul(np.linalg.pinv(x), y)
def test(self, x):
"""infer via elm
Args:
x (numpy.ndarray): (bsz, hidden_dim)
Returns:
y (numpy.ndarray): (bsz, ) predict results
"""
assert x.shape[1] == self.w.shape[0]
x = np.matmul(x, self.w) + self.b
x = self.act(x)
y = np.matmul(x, self.beta)
return y
def infer(self, x):
"""infer via elm
Args:
x (numpy.ndarray): (bsz, hidden_dim)
Returns:
y (numpy.ndarray): (bsz, ) predict labels
"""
labels = self.test(x) > 0.5
return labels.astype(np.int)
def act_func(self, act):
if act == 'tanh':
return np.tanh
elif act == 'sigmoid':
return lambda x: 1/(1+np.exp(-x))
else:
return lambda x: x
class classic_ELM:
def __init__(self, input_dim, hidden_dim, act='sigmoid', norm=None, classes=2):
"""ELM for classify problem
Args:
input_shape (int): number of input features
hidden_dim (int): number of hidden layer
act (str, optional): activite function. Defaults to 'sigmoid'.
norm (float or None, optional): normalize coefficient. Defaults to None.
classes (int, optional): classes number. Defaults to 2.
"""
if (input_dim is not None) and (hidden_dim is not None):
self.use_linear = True
self.w = np.random.rand(1, classes, input_dim, hidden_dim)
self.b = np.random.rand(1, classes, 1, hidden_dim)
self.act = self.act_func(act)
self.beta = np.random.rand(1, classes, hidden_dim, 1)
else:
self.use_linear = False
self.w = self.b = self.act = None
self.beta = np.random.rand(1)
self.C = norm
self.classes = classes
self.input_shape = input_dim
self.hidden_dim = hidden_dim
assert (self.C is None) or (type(1.0/self.C) is float)
def train(self, x, y):
"""train classic elm(specific elm for classify problem)
Args:
x (numpy.ndarray): (bsz, hidden_dim) train examples
y (numpy.ndarray): (bsz, ) labels
"""
bsz, h_0 = x.shape
if self.use_linear:
assert h_0 == self.input_shape
x = np.reshape(x, (bsz, 1, 1, h_0))
x = np.matmul(x, self.w) + self.b
x = self.act(x)
else:
x = np.reshape(x, (bsz, self.classes, 1, -1))
# change into one-hot label
y = np.eye(self.classes)[y.astype(np.int)]
y = y.T.reshape(-1, bsz, 1)
if self.C:
x = x.transpose([2, 1, 0, 3])
x_t = x.transpose(0, 1, 3, 2)
x_norm = np.matmul(x_t, x) + 1.0/self.C
x_inv = np.matmul(np.linalg.pinv(x_norm), x_t)
self.beta = np.matmul(x_inv, y)
else:
x = x.transpose([2, 1, 0, 3])
x_inv = np.linalg.pinv(x)
self.beta = np.matmul(x_inv, y)
def test(self, x):
"""infer via elm
Args:
x (numpy.ndarray): (bsz, hidden_dim)
Returns:
y (numpy.ndarray): (bsz, classes) predict probability
"""
bsz, h_0 = x.shape
if self.use_linear:
assert h_0 == self.input_shape
x = np.reshape(x, (bsz, 1, 1, h_0))
x = np.matmul(x, self.w) + self.b
x = self.act(x)
else:
x = np.reshape(x, (bsz, self.classes, 1, -1))
y = np.matmul(x, self.beta)
return y
def infer(self, x):
"""infer via elm
Args:
x (numpy.ndarray): (bsz, hidden_dim)
Returns:
y (numpy.ndarray): (bsz, ) predict labels
"""
y = self.test(x)
y = np.argmax(y, axis=1).squeeze()
return y
def act_func(self, act):
if act == 'tanh':
return np.tanh
elif act == 'sigmoid':
return lambda x: 1/(1+np.exp(-x))
else:
return lambda x: x
class normal_ELM:
def __init__(self, input_shape, output_shape, act='sigmoid', norm=1) -> None:
self.w = np.random.rand(input_shape, output_shape)
self.b = np.random.rand(output_shape)
self.beta = np.random.rand(output_shape, 1)
self.act = self.act_func(act)
self.C = norm
def train(self, x, y):
"""train normalized elm
Args:
x (numpy.ndarray): (bsz, hidden_dim) train examples
y (numpy.ndarray): (bsz, ) labels
"""
assert x.shape[1] == self.w.shape[0]
x = np.matmul(x, self.w) + self.b
shape = x.shape
x = self.act(x.flatten())
x = np.reshape(x, shape)
self.beta = np.matmul(np.matmul(
np.linalg.pinv(np.matmul(x.T, x) + 1/self.C), x.T), y)
# self.beta = np.matmul(np.linalg.pinv(x), y)
def test(self, x):
"""infer via elm
Args:
x (numpy.ndarray): (bsz, hidden_dim)
Returns:
y (numpy.ndarray): (bsz, ) predict results
"""
assert x.shape[1] == self.w.shape[0]
x = np.matmul(x, self.w) + self.b
x = self.act(x)
y = np.matmul(x, self.beta)
return y
def infer(self, x):
labels = self.test(x) > 0.5
labels = labels.astype(np.int)
return labels
def act_func(self, act):
if act == 'tanh':
return np.tanh
elif act == 'sigmoid':
return lambda x: 1/(1+np.exp(-x))
else:
return lambda x: x