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 __all__ = [
26 'RegressionDataset',
27 'LinearRegressor',
28 'train_LinearRegressor'
29 ]
30
31 from numpy import array, zeros, dot, prod
32 from scipy.linalg import pinv
33
34 from pycv.cs.stats import statslist, mean, moment1, correlation, moment11
35 from pycv import tprint
36 from pycv.cs.ml import Predictor, Dataset
37
38
39
40
42 - def __init__(self, input_data, output_data, weights = None ):
43 Dataset.__init__(self,len(input_data))
44 self.ishape = input_data[0].shape
45 self.isize = prod(self.ishape)
46 self.oshape = output_data[0].shape
47 self.osize = prod(self.oshape)
48 self.input_data = input_data
49 self.output_data = output_data
50 self.weights = weights
51
52
53
54
55
57 - def __init__( self, ishape, oshape, A = None, b = None):
58 self.ishape = ishape
59 self.oshape = oshape
60 if A is None:
61 self.A = zeros(ishape+oshape)
62 else:
63 self.A = A
64 if b is None:
65 self.b = zeros(oshape)
66 else:
67 self.b = b
68
69 - def predict(self, input_point, *args, **kwds):
70 return (dot(self.A,input_point.ravel())+self.b).reshape(self.oshape)
71
72
74 """Train a LinearRegressor using a RegressionDataset
75
76 Input:
77 regression_dataset: a RegressionDataset
78 Output:
79 a LinearRegressor
80 """
81
82 rd = regression_dataset
83 idata = rd.input_data.reshape(rd.N,rd.isize)
84 odata = rd.output_data.reshape(rd.N,rd.osize)
85
86 n, m1, cov1 = statslist(idata,rd.weights)
87 m2 = mean(n,moment1(odata,weights))
88 cor = correlation(n,moment11(idata,odata,weights),m1,m2)
89
90 self.A = dot(pinv(cov1),cor).T
91 self.b = m2 - dot(self.A,m1)
92
93 return LinearRegressor(rd.ishape,rd.oshape,A,b)
94