-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSymbolic_KANLayer.py
More file actions
237 lines (209 loc) · 7.8 KB
/
Copy pathSymbolic_KANLayer.py
File metadata and controls
237 lines (209 loc) · 7.8 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
229
230
231
232
233
234
235
236
237
import torch
import torch.nn as nn
import numpy as np
import sympy
from utils import *
class Symbolic_KANLayer(nn.Module):
'''
KANLayer class
Attributes:
-----------
in_dim: int
input dimension
out_dim: int
output dimension
funs: 2D array of torch functions (or lambda functions)
symbolic functions (torch)
funs_name: 2D arry of str
names of symbolic functions
funs_sympy: 2D array of sympy functions (or lambda functions)
symbolic functions (sympy)
affine: 3D array of floats
affine transformations of inputs and outputs
Methods:
--------
__init__():
initialize a Symbolic_KANLayer
forward():
forward
get_subset():
get subset of the KANLayer (used for pruning)
fix_symbolic():
fix an activation function to be symbolic
'''
def __init__(self, in_dim=3, out_dim=2, device='cpu'):
'''
initialize a Symbolic_KANLayer (activation functions are initialized to be identity functions)
Args:
-----
in_dim : int
input dimension
out_dim : int
output dimension
device : str
device
Returns:
--------
self
Example
-------
>>> sb = Symbolic_KANLayer(in_dim=3, out_dim=3)
>>> len(sb.funs), len(sb.funs[0])
(3, 3)
'''
super(Symbolic_KANLayer, self).__init__()
self.out_dim = out_dim
self.in_dim = in_dim
self.mask = torch.nn.Parameter(torch.zeros(out_dim, in_dim, device=device)).requires_grad_(False)
# torch
self.funs = [[lambda x: x for i in range(self.in_dim)] for j in range(self.out_dim)]
# name
self.funs_name = [['' for i in range(self.in_dim)] for j in range(self.out_dim)]
# sympy
self.funs_sympy = [['' for i in range(self.in_dim)] for j in range(self.out_dim)]
self.affine = torch.nn.Parameter(torch.zeros(out_dim, in_dim, 4, device=device))
# c*f(a*x+b)+d
self.device = device
def forward(self, x):
'''
forward
Args:
-----
x : 2D array
inputs, shape (batch, input dimension)
Returns:
--------
y : 2D array
outputs, shape (batch, output dimension)
postacts : 3D array
activations after activation functions but before summing on nodes
Example
-------
>>> sb = Symbolic_KANLayer(in_dim=3, out_dim=5)
>>> x = torch.normal(0,1,size=(100,3))
>>> y, postacts = sb(x)
>>> y.shape, postacts.shape
(torch.Size([100, 5]), torch.Size([100, 5, 3]))
'''
batch = x.shape[0]
postacts = []
for i in range(self.in_dim):
postacts_ = []
for j in range(self.out_dim):
xij = self.affine[j,i,2]*self.funs[j][i](self.affine[j,i,0]*x[:,[i]]+self.affine[j,i,1])+self.affine[j,i,3]
postacts_.append(self.mask[j][i]*xij)
postacts.append(torch.stack(postacts_))
postacts = torch.stack(postacts)
postacts = postacts.permute(2,1,0,3)[:,:,:,0]
y = torch.sum(postacts, dim=2)
return y, postacts
def get_subset(self, in_id, out_id):
'''
get a smaller Symbolic_KANLayer from a larger Symbolic_KANLayer (used for pruning)
Args:
-----
in_id : list
id of selected input neurons
out_id : list
id of selected output neurons
Returns:
--------
spb : Symbolic_KANLayer
Example
-------
>>> sb_large = Symbolic_KANLayer(in_dim=10, out_dim=10)
>>> sb_small = sb_large.get_subset([0,9],[1,2,3])
>>> sb_small.in_dim, sb_small.out_dim
(2, 3)
'''
sbb = Symbolic_KANLayer(self.in_dim, self.out_dim, device=self.device)
sbb.in_dim = len(in_id)
sbb.out_dim = len(out_id)
sbb.mask.data = self.mask.data[out_id][:,in_id]
sbb.funs = [[self.funs[j][i] for i in in_id] for j in out_id]
sbb.funs_sympy = [[self.funs_sympy[j][i] for i in in_id] for j in out_id]
sbb.funs_name = [[self.funs_name[j][i] for i in in_id] for j in out_id]
sbb.affine.data = self.affine.data[out_id][:,in_id]
return sbb
def fix_symbolic(self, i, j, fun_name, x=None, y=None, random=False, a_range=(-10,10), b_range=(-10,10), verbose=True):
'''
fix an activation function to be symbolic
Args:
-----
i : int
the id of input neuron
j : int
the id of output neuron
fun_name : str
the name of the symbolic functions
x : 1D array
preactivations
y : 1D array
postactivations
a_range : tuple
sweeping range of a
b_range : tuple
sweeping range of a
verbose : bool
print more information if True
Returns:
--------
r2 (coefficient of determination)
Example 1
---------
>>> # when x & y are not provided. Affine parameters are set to a = 1, b = 0, c = 1, d = 0
>>> sb = Symbolic_KANLayer(in_dim=3, out_dim=2)
>>> sb.fix_symbolic(2,1,'sin')
>>> print(sb.funs_name)
>>> print(sb.affine)
[['', '', ''], ['', '', 'sin']]
Parameter containing:
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[1., 0., 1., 0.]], requires_grad=True)
Example 2
---------
>>> # when x & y are provided, fit_params() is called to find the best fit coefficients
>>> sb = Symbolic_KANLayer(in_dim=3, out_dim=2)
>>> batch = 100
>>> x = torch.linspace(-1,1,steps=batch)
>>> noises = torch.normal(0,1,(batch,)) * 0.02
>>> y = 5.0*torch.sin(3.0*x + 2.0) + 0.7 + noises
>>> sb.fix_symbolic(2,1,'sin',x,y)
>>> print(sb.funs_name)
>>> print(sb.affine[1,2,:].data)
r2 is 0.9999701976776123
[['', '', ''], ['', '', 'sin']]
tensor([2.9981, 1.9997, 5.0039, 0.6978])
'''
if isinstance(fun_name,str):
fun = SYMBOLIC_LIB[fun_name][0]
fun_sympy = SYMBOLIC_LIB[fun_name][1]
self.funs_sympy[j][i] = fun_sympy
self.funs_name[j][i] = fun_name
if x == None or y == None:
#initialzie from just fun
self.funs[j][i] = fun
if random == False:
self.affine.data[j][i] = torch.tensor([1.,0.,1.,0.])
else:
self.affine.data[j][i] = torch.rand(4,) * 2 - 1
return None
else:
#initialize from x & y and fun
params, r2 = fit_params(x,y,fun, a_range=a_range, b_range=b_range, verbose=verbose, device=self.device)
self.funs[j][i] = fun
self.affine.data[j][i] = params
return r2
else:
# if fun_name itself is a function
fun = fun_name
fun_sympy = fun_name
self.funs_sympy[j][i] = fun_sympy
self.funs_name[j][i] = "anonymous"
self.funs[j][i] = fun
if random == False:
self.affine.data[j][i] = torch.tensor([1.,0.,1.,0.])
else:
self.affine.data[j][i] = torch.rand(4,) * 2 - 1
return None