1 | from pylab import *
|
2 | import cv2 as cv
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | step_size = 0.01
|
9 |
|
10 |
|
11 | momentum = 0.0
|
12 |
|
13 |
|
14 | nsteps = 10000
|
15 |
|
16 |
|
17 | max_err = 0.0001
|
18 |
|
19 |
|
20 | condition = cv.TERM_CRITERIA_COUNT | cv.TERM_CRITERIA_EPS
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | criteria = (condition, nsteps, max_err)
|
26 |
|
27 |
|
28 | params = dict( term_crit = criteria,
|
29 | train_method = cv.ANN_MLP_TRAIN_PARAMS_BACKPROP,
|
30 | bp_dw_scale = step_size,
|
31 | bp_moment_scale = momentum )
|
32 |
|
33 |
|
34 |
|
35 | layer_sizes = array([1,52,2])
|
36 | mlp = cv.ANN_MLP(layer_sizes)
|
37 |
|
38 |
|
39 | x = linspace(0,1)
|
40 | y1 = (sin(x*2*pi)+1)/2.
|
41 | y2 = (cos(x*2*pi)+1)/2.
|
42 | y = hstack((y1.reshape(-1,1),y2.reshape(-1,1)))
|
43 |
|
44 | z = zeros_like(y)+.5
|
45 |
|
46 |
|
47 | print "Notice that z is Fortran contiguous, rather than C contiguous:"
|
48 | print z.flags
|
49 | print "When performing a lot of vstack and hstack operations, for"
|
50 | print "efficiency reasons, sometimes Numpy will switch continuity."
|
51 |
|
52 |
|
53 | inpt = x
|
54 | inpt = hstack((inpt,inpt))
|
55 | inpt = hstack((inpt,inpt))
|
56 | inpt = hstack((inpt,inpt))
|
57 | outpt = y
|
58 | outpt = vstack((outpt,outpt))
|
59 | outpt = vstack((outpt,outpt))
|
60 | outpt = vstack((outpt,outpt))
|
61 |
|
62 |
|
63 | mlp.train(inpt,outpt,None,params=params)
|
64 | mlp.predict(x,z)
|
65 |
|
66 |
|
67 |
|
68 | figure()
|
69 | title("first dimension of training data\n (dots should line up on the sine curve)")
|
70 | plot(x,y[:,0],'b')
|
71 | plot(x,z[:,0],'go')
|
72 |
|
73 |
|
74 |
|
75 | figure()
|
76 | title("second dimension of training data\n (dots should line up on the cosine curve)")
|
77 | plot(x,y[:,1],'r')
|
78 | plot(x,z[:,1],'yo')
|
79 | show() |