7
from scipy.optimize import leastsq
10
"""Class to define/train/test a radial basis function network
14
_outfxns = ('linear','logistic','softmax')
17
def __init__(self,ni,no,f='linear'):
18
""" Set up instance of RBF net. N.B. RBF centers and variance are selected at training time
20
ni - <int> # of inputs
21
no - <int> # of outputs
22
f - <str> output activation fxn
30
""" Decompose 1-d vector of weights w into appropriate weight
31
matrices (self.{w/b}) and reinsert them into net
33
self.w = N.array(self.wp)[:self.centers.shape[0]*self.no].reshape(self.centers.shape[0],self.no)
34
self.b = N.array(self.wp)[(self.centers.shape[0]*self.no):].reshape(1,self.no)
37
""" Compile weight matrices w,b from net into a
38
single vector, suitable for optimization routines.
40
self.wp = N.hstack([self.w.reshape(N.size(self.w)),
41
self.b.reshape(N.size(self.b))])
43
def fwd_all(self,X,w=None):
44
""" Propagate values forward through the net.
46
inputs - vector of input values
47
w - packed array of weights
49
array of outputs for all input patterns
54
# compute hidden unit values
55
z = N.zeros((len(X),self.centers.shape[0]))
56
for i in range(len(X)):
57
z[i] = N.exp((-1.0/(2*self.variance))*(N.sum((X[i]-self.centers)**2,axis=1)))
59
o = N.dot(z,self.w) + N.dot(N.ones((len(z),1)),self.b)
60
# compute final output activations
61
if self.outfxn == 'linear':
63
elif self.outfxn == 'logistic': # TODO: check for overflow here...
65
elif self.outfxn == 'softmax': # TODO: and here...
67
y = tmp/(N.sum(temp,1)*N.ones((1,self.no)))
72
def err_fxn(self,w,X,Y):
73
""" Return vector of squared-errors for the leastsq optimizer
76
return N.sum(N.array(O-Y)**2,axis=1)
79
""" Train RBF network:
80
(i) select fixed centers randomly from input data (10%)
81
(ii) set fixed variance from max dist between centers
82
(iii) learn output weights using scipy's leastsq optimizer
84
# set centers & variance
85
self.centers = N.array(random.sample(X,len(X)/10))
87
for i in self.centers:
88
for j in self.centers:
89
tmp = N.sum(N.sqrt((i-j)**2))
92
self.variance = d_max/(2.0*len(X))
94
self.nw = self.centers.shape[0]*self.no
95
self.w = N.random.randn(self.centers.shape[0],self.no)/N.sqrt(self.centers.shape[0]+1)
96
self.b = N.random.randn(1,self.no)/N.sqrt(self.centers.shape[0]+1)
98
self.wp = leastsq(self.err_fxn,self.wp,args=(X,Y))[0]
100
def test_all(self,X,Y):
101
""" Test network on an array (size>1) of patterns
103
x - array of input data
106
sum-squared-error over all data
108
return N.sum(self.err_fxn(self.wp,X,Y))
111
""" Build/train/test RBF net
113
from scipy.io import read_array
114
print "\nCreating RBF net"
116
print "\nLoading training and test sets...",
117
X_trn = read_array('data/oil-trn.dat',columns=(0,(1,12)),lines=(3,-1))
118
Y_trn = read_array('data/oil-trn.dat',columns=(12,-1),lines=(3,-1))
119
X_tst = read_array('data/oil-tst.dat',columns=(0,(1,12)),lines=(3,-1))
120
Y_tst = read_array('data/oil-tst.dat',columns=(12,-1),lines=(3,-1))
122
#print "\nInitial SSE:\n"
123
#print "\ttraining set: ",net.test_all(X_trn,Y_trn)
124
#print "\ttesting set: ",net.test_all(X_tst,Y_tst),"\n"
126
net.train(X_trn,Y_trn)
128
print "\nFinal SSE:\n"
129
print "\ttraining set: ",net.test_all(X_trn,Y_trn)
130
print "\ttesting set: ",net.test_all(X_tst,Y_tst),"\n"
133
if __name__ == '__main__':