Perceptron: Difference between revisions

m (→‎{{header|REXX}}: minor correction)
Line 778:
#####OOOOOOOOOOOOOOO
####OOOOOOOOOOOOOOOO</pre>
 
=={{header|Phix}}==
Interactive GUI version. Select one of five lines, set the number of points, learning constant,
learning rate, and max iterations. Plots accuracy vs. iterations and displays the training data
in blue/black=above/incorrect and green/red=below/incorrect [all blue/green = 100% accurate].
<lang Phix>-- demo\rosetta\Perceptron.exw
--
-- The learning curve turned out more haphazard than I imagined, and adding a
-- non-linear line to f() (case 5) was perhaps not such a great idea given how
-- much it sometimes struggles with some of the other straight lines anyway.
--
include pGUI.e
--#withtype Ihandle
--#withtype Ihandles
--#withtype cdCanvas
 
constant help_txt = """
A perceptron is the simplest possible neural network, consisting of just one neuron
that we train to recognise whether a point is above or below a given straight line.
NB: It would probably be unwise to overly assume that this could easily be adapted
to anything more complex, or actually useful. It is just a basic introduction, but
you have to start somewhere. What is interesting is that ultimately the neuron is
just three numbers, plus a bucket-load of training gumpf.
 
The left hand panel allows settings to be changed, in the middle we plot the rate of
learning, and on the right we show the training data colour coded as above/below and
correct/incorrect (blue/black=above/incorrect, green/red=below/incorrect). What you
want to see is all blue/green, with no black/red.
 
You can change the line algorithm (four straight and one curved that it is not meant
to be able to cope with), the number of points (size of training data), the learning
constant, learning rate (iterations/second) and the maximum number of iterations.
Note that training automatically stops once 100% accuracy is reached (since the error
is then always zero, no further changes would ever occur). Also note that a restart
is triggered when any setting is changed, not just when the restart button is pressed.
 
The learning curve was expected to start at 50% (random chance of being right) and
gradually improve towards 100%, except when the non-linear line was selected. It
turned out far more haphazard than I thought it would. Originally it allowed up to
10,000,000 iterations, but it rarely improved much beyond 1,000,000."""
 
function help_cb(Ihandln /*help*/)
IupMessage("Perceptron",help_txt)
return IUP_DEFAULT
end function
 
Ihandle dlg, plot, canvas, timer,
iteration, accuracy, w1, w2, w3
cdCanvas cddbuffer, cdcanvas
 
integer line_alg = 1
integer points = 2000,
learning_rate = 10000,
max_iterations = 1_000_000,
total_iterations = 0
atom learning_constant = 0.00001
 
enum WEIGHTS, -- The actual neuron (just 3 numbers)
TRAINING -- training data/results, variable length
enum INPUTS, ANSWER -- contents of [TRAINING]
-- note that length(inputs[i]) must = length(weights)
 
sequence perceptron = {},
last_wh -- (recreate "" on resize)
 
function activate(atom t)
return iff(t>0?+1:-1)
end function
 
function f(atom x)
switch line_alg
case 1: return x*0.7+40
case 2: return 300-0.3*x
case 3: return x*0.75
case 4: return 2*x+1
case 5: return x/2+sin(x/100)*100+100 -- (fail)
end switch
end function
 
procedure new_perceptron(integer n)
sequence weights := repeat(0, n)
for i=1 to n do
weights[i] = rnd()*2 - 1
end for
sequence training := repeat(0,points)
integer {w,h} = last_wh
for i=1 to points do
integer x := rand(w),
y := rand(h),
answer := activate(y-f(x))
sequence inputs = {x, y, 1}
-- aside: inputs is {x,y,1}, rather than {x,y} because an
-- input of {0,0} could only ever yield 0, whereas
-- {0,0,1} can yield a non-zero guess: weights[3].
training[i] = {inputs, answer} -- {INPUTS, ANSWER}
end for
perceptron = {weights, training} -- {WEIGHTS, TRAINING}
end procedure
function feed_forward(sequence inputs)
if length(inputs)!=length(perceptron[WEIGHTS]) then
throw("weights and input length mismatch, program terminated")
end if
atom total := 0.0
for i=1 to length(inputs) do
total += inputs[i] * perceptron[WEIGHTS][i]
end for
return activate(total)
end function
procedure train(sequence inputs, integer desired)
integer guess := feed_forward(inputs),
error := desired - guess
for i=1 to length(perceptron[WEIGHTS]) do
perceptron[WEIGHTS][i] += learning_constant * error * inputs[i]
end for
end procedure
--DEV add to pGUI/doc
procedure cdCanvasCircle(cdCanvas cddbuffer, atom x, y, r)
cdCanvasArc(cddbuffer,x,y,r,r,0,360)
end procedure
 
function draw(bool bDraw=true)
-- (if bDraw is false, we just want the "correct" count)
integer correct = 0
atom x, y
for i=1 to points do
{sequence inputs, integer answer} = perceptron[TRAINING][i]
integer guess := feed_forward(inputs)
correct += (guess=answer)
if bDraw then
{x,y} = inputs
-- blue/black=above/incorrect, green/red=below/incorrect
integer clr = iff(guess=answer?iff(guess>0?CD_BLUE:CD_GREEN)
:iff(guess>0?CD_BLACK:CD_RED))
cdCanvasSetForeground(cddbuffer, clr)
cdCanvasCircle(cddbuffer, x, y, 8)
end if
end for
if bDraw then
cdCanvasSetForeground(cddbuffer, CD_BLACK)
x := last_wh[1]
y := f(x)
if line_alg=5 then
-- non-linear so (crudely) draw in little segments
for i=0 to x by 20 do
cdCanvasLine(cddbuffer,i,f(i),i+20,f(i+20))
end for
else
cdCanvasLine(cddbuffer,0,f(0),x,y)
end if
end if
return correct
end function
bool re_plot = true
atom plot0
sequence plotx = repeat(0,19),
ploty = repeat(0,19)
integer imod = 1, -- keep every 1, then 10, then 100, ...
pidx = 1
 
function restart_cb(Ihandln /*restart*/)
last_wh = IupGetIntInt(canvas, "DRAWSIZE")
new_perceptron(3)
imod = 1
pidx = 1
total_iterations = 0
plot0 = (draw(false)/points)*100
re_plot = true
IupSetInt(timer,"RUN",1)
return IUP_DEFAULT
end function
 
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
if perceptron={}
or last_wh!=IupGetIntInt(canvas, "DRAWSIZE") then
{} = restart_cb(NULL)
end if
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
integer correct = draw()
cdCanvasFlush(cddbuffer)
 
if re_plot then
re_plot = false
IupSetAttribute(plot, "CLEAR", NULL)
IupPlotBegin(plot)
IupPlotAdd(plot, 0, plot0)
for i=1 to pidx-1 do
IupPlotAdd(plot, plotx[i], ploty[i])
end for
{} = IupPlotEnd(plot)
IupSetAttribute(plot, "REDRAW", NULL)
end if
IupSetStrAttribute(iteration,"TITLE","iteration: %d",{total_iterations})
IupSetStrAttribute(w1,"TITLE","%+f",{perceptron[WEIGHTS][1]})
IupSetStrAttribute(w2,"TITLE","%+f",{perceptron[WEIGHTS][2]})
IupSetStrAttribute(w3,"TITLE","%+f",{perceptron[WEIGHTS][3]})
IupSetStrAttribute(accuracy,"TITLE","accuracy: %.4g%%",{(correct/points)*100})
IupRefresh({iteration,w1,w2,w3,accuracy}) -- (force label resize)
if correct=points then
IupSetInt(timer,"RUN",0) -- stop at 100%
end if
return IUP_DEFAULT
end function
 
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_PARCHMENT)
return IUP_DEFAULT
end function
 
function valuechanged_cb(Ihandle ih)
string name = IupGetAttribute(ih, "NAME")
integer v = IupGetInt(ih, "VALUE")
switch name
case "line": line_alg = v
case "points": points = power(10,v)
case "learn": learning_constant = power(10,-v)
case "rate": learning_rate = power(10,v-1)
case "max": max_iterations = power(10,v)
end switch
{} = restart_cb(NULL)
return IUP_DEFAULT
end function
 
function timer_cb(Ihandle /*timer*/)
for i=1 to min(learning_rate,max_iterations) do
total_iterations += 1
integer c = mod(total_iterations,points)+1
train(perceptron[TRAINING][c][INPUTS], perceptron[TRAINING][c][ANSWER])
if mod(total_iterations,imod)=0 then
-- save 1,2..10, then 20,30,..100, then 200,300,..1000, etc
re_plot = true
plotx[pidx] = total_iterations
ploty[pidx] = (draw(false)/points)*100
if pidx=10 or pidx=19 then
if pidx=19 then
-- drop (eg) 1,2,..9, replace with 10,20,..90,
-- next time replace 10,20..90 with 100,200..900, etc
plotx[1..10] = plotx[10..19]
ploty[1..10] = ploty[10..19]
end if
imod *= 10
pidx = 11
else
pidx += 1
end if
end if
end for
if total_iterations>=max_iterations then
IupSetInt(timer,"RUN",0)
end if
IupUpdate(canvas)
return IUP_IGNORE
end function
 
function esc_close(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if c=K_F1 then return help_cb(NULL) end if
if c=K_F5 then return restart_cb(NULL) end if
return IUP_CONTINUE
end function
 
function settings(string lname, name, sequence opts, integer v=1)
Ihandle lbl = IupLabel(lname,"PADDING=0x4"),
list = IupList("NAME=%s, DROPDOWN=YES",{name}),
hbox = IupHbox({lbl,IupFill(),list})
for i=1 to length(opts) do
IupSetAttributeId(list,"",i,opts[i])
end for
IupSetInt(list,"VISIBLEITEMS",length(opts)+1)
IupSetInt(list,"VALUE",v)
IupSetCallback(list, "VALUECHANGED_CB", Icallback("valuechanged_cb"));
return hbox
end function
 
function sep()
return IupLabel("","SEPARATOR=HORIZONTAL")
end function
 
procedure main()
IupOpen()
IupControlsOpen()
 
Ihandle settings_lbl = IupHbox({IupFill(),IupLabel("Settings"),IupFill()}),
line = settings("line","line",{"x*0.7 + 40","300 - 0.3*x","x*0.75","2*x + 1","x/2+sin(x/100)*100+100"}),
points = settings("number of points","points",{"10","100","1000","10000"},3),
learn = settings("learning constant","learn",{"0.1","0.01","0.001","0.0001","0.00001"},5),
rate = settings("learning rate","rate",{"1/s","10/s","100/s","1000/s","10000/s"},5),
maxiter = settings("max iterations","max",{"10","100","1000","10,000","100,000","1,000,000"},6),
restart = IupButton("Restart (F5)", "ACTION", Icallback("restart_cb")),
helpbtn = IupButton("Help (F1)", "ACTION", Icallback("help_cb")),
buttons = IupHbox({restart,IupFill(),helpbtn})
 
iteration = IupLabel("iteration: 1")
w1 = IupLabel("1")
w2 = IupLabel("2")
w3 = IupLabel("3")
Ihandle weights = IupHbox({IupLabel("weights: ","PADDING=0x4"),IupVbox({w1,w2,w3})})
accuracy = IupLabel("accuracy: 12.34%")
 
Ihandle vbox = IupVbox({settings_lbl, sep(),
line, sep(), points, sep(), learn, sep(),
rate, sep(), maxiter, sep(), buttons, sep(),
IupHbox({iteration}), weights, IupHbox({accuracy})})
IupSetAttribute(vbox, "GAP", "4");
 
plot = IupPlot("MENUITEMPROPERTIES=Yes")
IupSetAttribute(plot, "TITLE", "Learning Curve");
IupSetAttribute(plot, "TITLEFONTSIZE", "10");
IupSetAttribute(plot, "TITLEFONTSTYLE", "ITALIC");
IupSetAttribute(plot, "GRIDLINESTYLE", "DOTTED");
IupSetAttribute(plot, "GRID", "YES");
IupSetAttribute(plot, "AXS_XLABEL", "iterations");
IupSetAttribute(plot, "AXS_YLABEL", "% correct");
IupSetAttribute(plot, "AXS_XFONTSTYLE", "ITALIC");
IupSetAttribute(plot, "AXS_YFONTSTYLE", "ITALIC");
IupSetAttribute(plot, "AXS_XTICKNUMBER", "No");
IupSetAttribute(plot, "AXS_YAUTOMIN", "No");
IupSetAttribute(plot, "AXS_YAUTOMAX", "No");
IupSetInt(plot, "AXS_YMIN", 0)
IupSetInt(plot, "AXS_YMAX", 100)
 
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "640x360") -- initial size
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
 
Ihandle hbox = IupHbox({vbox, plot, canvas},"MARGIN=4x4, GAP=10")
dlg = IupDialog(hbox);
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
IupSetAttribute(dlg, "TITLE", "Perceptron")
IupMap(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release limitation
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
timer = IupTimer(Icallback("timer_cb"), 100) -- (was 1 sec, now 0.1s)
IupMainLoop()
IupClose()
end procedure
main()</lang>
 
=={{header|Racket}}==
7,805

edits