En este ejemplo creamos un objeto TPerceptron y le hacemos aprender el comportamiento de la función nAnd(), a continuación comprobamos los resultados y parecen correctos.
Acto seguido, creamos un nuevo objeto TPerceptron y le enseñamos el comportamiento de la función nOr(), los resultados parecen correctos nuevamente
No soy ningún experto en IA, solo tengo curiosidad al respecto. Agradezco vuestros comentarios y pruebas
perceptron.prg
- Code: Select all Expand view
- #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 )