-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlearn_gest.py
261 lines (212 loc) · 7.8 KB
/
learn_gest.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
254
255
256
257
258
259
260
261
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets import SupervisedDataSet
import mapper
import Tkinter
import tkFileDialog
import sys
#./mapperRec.exe -m tkgui -b file -f tkgui.txt
if (len(sys.argv)==4):
#print (sys.argv)
try:
num_inputs=int(sys.argv[1])
num_hidden=int(sys.argv[2])
num_outputs=int(sys.argv[3])
print ("Input Arguments (#inputs, #hidden nodes, #outputs): " + str(num_inputs) + ", " + str(num_hidden) + ", " + str(num_outputs) )
except:
print ("Bad Input Arguments (#inputs, #hidden nodes, #outputs)")
sys.exit(1)
elif (len(sys.argv)>1):
print ("Bad Input Arguments (#inputs, #hidden nodes, #outputs)")
sys.exit(1)
else:
#number of network inputs
num_inputs=8
#number of network outputs
num_outputs=8
#number of hidden nodes
num_hidden=5
print ("No Input Arguments (#inputs, #hidden nodes, #outputs), defaulting to: " + str(num_inputs) + ", " + str(num_hidden) + ", " + str(num_outputs) )
#instatiate mapper
l_map=mapper.device("learn_mapper",9000)
l_inputs={}
l_outputs={}
data_input={}
data_output={}
learning = 0
compute = 0
for s_index in range(num_inputs):
data_input[s_index+10]=0.0
# data_input[s_index]=0.0
for s_index in range (num_outputs):
data_output[s_index]=0.0
sliders={}
master=Tkinter.Tk()
master.title("PyBrain Mapper Demo")
master.resizable(height=True, width=True)
master.geometry("500x500")
def main_loop():
global ds
if ((learning==1) and (compute ==0)):
print ("Inputs: ")
print (tuple(data_input.values()))
print ("Outputs: ")
print (tuple( data_output.values()))
# print ("input/output values: " + (tuple(data_input.values()),tuple(data_output.values())))
ds.addSample(tuple(data_input.values()),tuple(data_output.values()))
# if learning==1:
# pass
# if compute ==1:
# pass
l_map.poll(0)
def on_gui_change(x,s_index):
# s_index=0
try:
#print "in callback: on gui change"
#print x,s_index
global data_output
if (compute==0):
data_output[s_index]=float(x)/100.0
l_outputs[s_index].update(float(x)/100.0)
#print ("on gui change: ", data_output)
except:
print ("WTF MATE? On Gui Change Error!")
raise
for s_index in range(num_outputs):
def tc(s_index):
return lambda x: on_gui_change(x,s_index)
sliders[s_index]=Tkinter.Scale(master,from_=0,to=100, label='output'+str(s_index),orient=Tkinter.HORIZONTAL,length=300,command=tc(s_index))
sliders[s_index].pack()
def learn_callback():
global learning
if learning == 1:
b_learn.config(relief='raised',text="Acquire Training Data (OFF)",bg='gray')
learning=0
print ("learning is now OFF")
elif learning ==0:
b_learn.config(relief='sunken',text="Acquiring Training Data (ON)",bg='red')
learning=1
print ("learning is now ON")
print ("learning is", learning)
#b.learn_on.text="Acquire Training Data (ON)"
def compute_callback():
global compute
global net
global ds
if compute==1:
b_compute.config(relief='raised',text="Press to compute network outputs (OFF)",bg='gray')
compute =0
print ("Compute network output is now OFF!")
elif compute ==0:
#trainer.trainUntilConvergence()
b_compute.config(relief='sunken',text="Computing network outputs(ON)",bg='coral')
compute =1
print ("Comput network output is now ON!")
#print(dir(ds))
#print(ds['target'][0])
#print(ds['target'][1])
#print(ds[1,0])
#print(ds[1,1])
def train_callback():
trainer = BackpropTrainer(net, ds)
for train_round in range (40):
print(trainer.train())
print (trainer)
def clear_dataset():
ds.clear()
def save_dataset():
save_filename = tkFileDialog.asksaveasfilename()
ds.saveToFile(save_filename)
csv_file=open(save_filename+".csv",'w')
csv_file.write("[inputs][outputs]\r\n")
for inpt, tgt in ds:
new_str=str("{" + repr(inpt) + "," + repr(tgt) + "}")
# (repr(inpt) + repr(tgt))
new_str=new_str.strip('\n')
new_str=new_str.strip('\r')
new_str=new_str+"\r"
print(repr(new_str))
csv_file.write(new_str)
csv_file.close()
def load_dataset():
open_filename = tkFileDialog.askopenfilename()
global ds
ds=SupervisedDataSet.loadFromFile(open_filename)
def save_net():
from pybrain.tools.customxml import networkwriter
save_filename = tkFileDialog.asksaveasfilename()
networkwriter.NetworkWriter.writeToFile(net,save_filename)
def load_net():
from pybrain.tools.customxml import networkreader
open_filename = tkFileDialog.askopenfilename()
global net
net=networkreader.NetworkReader.readFrom(open_filename)
b_learn = Tkinter.Button(master, text="Acquire Training Data (OFF)", command=learn_callback)
b_learn.pack()
b_train =Tkinter.Button(master, text="Train Network", command=train_callback)
b_train.pack()
b_compute = Tkinter.Button(master, text="Compute Network Outputs", command=compute_callback)
b_compute.pack()
b_clear_data=Tkinter.Button(master, text="Clear data set",command = clear_dataset)
b_clear_data.pack()
b_save_dataset=Tkinter.Button(master, text='Save Current DataSet to file',command=save_dataset)
b_save_dataset.pack()
b_load_dataset=Tkinter.Button(master, text='Load DataSet from File',command=load_dataset)
b_load_dataset.pack()
b_save_net=Tkinter.Button(master, text='Save Current Network to File',command=save_net)
b_save_net.pack()
b_load_net=Tkinter.Button(master, text='Load Network from File',command=load_net)
b_load_net.pack()
def ontimer():
#print 'someshit'
main_loop()
# check the serial port
master.after(10, ontimer)
#mapper signal handler (updates data_input[sig_indx]=new_float_value)
def h(sig, f):
try:
#print "mapper signal handler"
#print (sig.name, f)
s_indx=str.split(sig.name,"/input/")
# print sig.name
global data_input
global data_output
data_input[int(s_indx[1])]=float(f/100.0)
# print(int(s_indx[1]),data_input[int(s_indx[1])])
# if (learning==1):
# print(int(s_indx[1]),data_input[int(s_indx[1])])
if ((compute==1) and (learning==0)):
#print ("inputs to net: ",data_input)
activated_out=net.activate(tuple(data_input.values()))
#print ("Activated outs: ", activated_out)
for out_index in range(num_outputs):
data_output[out_index]=activated_out[out_index]
sliders[out_index].set(int(activated_out[out_index]*100.0))
l_outputs[out_index].update(data_output[out_index])
except:
print "WTF, h handler not working"
#create mapper signals (inputs)
for l_num in range(num_inputs):
l_inputs[l_num]=l_map.add_input("/input/"+str(l_num+int(10)),'f',h,None,0,100.0)
# l_inputs[l_num]=l_map.add_input("/input/"+str(l_num),'f',h,None,0,100.0)
l_map.poll(0)
print ("creating input", "/input/"+str(l_num+int(10)))
# print ("creating input", "/input/"+str(l_num))
#create mapper signals (outputs)
for l_num in range(num_outputs):
# l_outputs[l_num]=l_map.add_output("/output/"+str(l_num+int(10)),'f',None,0,1)
l_outputs[l_num]=l_map.add_output("/output/"+str(l_num),'f',None,0,1)
l_map.poll(0)
# print ("creating output","/output/"+str(l_num+int(10)))
print ("creating output","/output/"+str(l_num))
#create network
net = buildNetwork(num_inputs,num_hidden,num_outputs,bias=True)
#create dataSet
ds = SupervisedDataSet(num_inputs, num_outputs)
#while (True):
ontimer()
#master.after(500, ontimer)
master.protocol("WM_DELETE_WINDOW", master.quit)
master.mainloop()
master.destroy()
del master