In this example we create a TPerceptron object and we make it learn the behavior of the function nAnd(), then we check the results and they seem to be right.
Then we create a new TPerceptron object and we make it learn the behavior of the function nOr(), the results seem right again
I am not an expert at all on IA, I am just curious about it. So I appreciate your comments and tests
perceptron.prg
Code: Select all
#include "FiveWin.ch"
function Main()
local oPerceptron := TPerceptron():New( 2 )
local n, nX, nY
// the perceptron learns nAnd()
for n = 1 to 1000
oPerceptron:Learn( { nX := nRandom( 1 ), nY := nRandom( 1 ) }, nAnd( nX, nY ) )
next
MsgInfo( oPerceptron:CalculateOutput( { 1, 1 } ), "1" )
MsgInfo( oPerceptron:CalculateOutput( { 1, 0 } ), "0" )
MsgInfo( oPerceptron:CalculateOutput( { 0, 1 } ), "0" )
MsgInfo( oPerceptron:CalculateOutput( { 0, 0 } ), "0" )
// We create a new perceptron to learn nOr()
oPerceptron := TPerceptron():New( 2 )
for n = 1 to 1000
oPerceptron:Learn( { nX := nRandom( 1 ), nY := nRandom( 1 ) }, nOr( nX, nY ) )
next
MsgInfo( oPerceptron:CalculateOutput( { 1, 1 } ), "1" )
MsgInfo( oPerceptron:CalculateOutput( { 1, 0 } ), "1" )
MsgInfo( oPerceptron:CalculateOutput( { 0, 1 } ), "1" )
MsgInfo( oPerceptron:CalculateOutput( { 0, 0 } ), "0" )
XBrowser( oPerceptron )
return nil
CLASS TPerceptron
DATA aPreviousWeights
DATA nPreviousThreshold
DATA aWeights
DATA nThreshold
DATA nLearningRate
METHOD New( nInputs )
METHOD Learn( aInputs, nExpectedOutput )
METHOD CalculateOutput( aInputs )
ENDCLASS
METHOD New( nInputs ) CLASS TPerceptron
local n
::nPreviousThreshold = 0
::aWeights = Array( nInputs )
::aPreviousWeights = Array( nInputs )
::nThreshold = 0
::nLearningRate = 0.1
for n = 1 to nInputs
::aPreviousWeights[ n ] = 0
::aWeights[ n ] = 0
next
return Self
METHOD Learn( aInputs, nExpectedOutput ) CLASS TPerceptron
local nError := nExpectedOutput - ::CalculateOutput( aInputs )
local n
for n = 1 to Len( ::aWeights )
::aWeights[ n ] = ::aPreviousWeights[ n ] + ::nLearningRate * nError * aInputs[ n ]
next
::nThreshold = ::nPreviousThreshold + ::nLearningRate * nError
::aPreviousWeights = ::aWeights
::nPreviousThreshold = ::nThreshold
return nil
METHOD CalculateOutput( aInputs ) CLASS TPerceptron
local nSum := 0
local n
for n = 1 to Len( ::aWeights )
nSum += aInputs[ n ] * ::aWeights[ n ]
next
nSum += ::nThreshold
return If( nSum > 0, 1, 0 )