Created
October 25, 2016 13:14
-
-
Save felipessalvatore/ca0cc2e4b94d8fec154f2c3c8b5c95da to your computer and use it in GitHub Desktop.
First try in training a neural network in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from pylab import norm | |
class BasicNN: | |
bias = 0.5 | |
weights = [] | |
def __init__(self, NEntradas): | |
for i in range(NEntradas): | |
self.weights.append(random.uniform(0,1)) | |
# atualizacao de pesos da rede, baseado no perceptron | |
# x_k é a k-ésima amostra do treinamento. | |
def treinamento(self, entrada, saidaDesejada, taxa): | |
# O algoritmo de treinamento devolve o erro. O erro é calculado com o seguinte principio: | |
# é o módulo resultado da subtração do valor desejado do valor obtido. | |
# Os pesos são reajustados de acordo com o erro obtido. | |
# peso_atual = peso_anterior + taxa_de_aprendizagem * (valor_desejado - valor_obtido) * x_k | |
auxErro=0 | |
Erro = 0 | |
for i in range(len(saidaDesejada)): | |
auxSum = 0.0 #esta variavel auxilia na soma das entradas | |
for j in range(len(entrada)): | |
auxSum += (entrada[j][i] * self.weights[j]) + self.bias | |
valor_obtido = self.transferencia(auxSum) | |
#print "valor_obtido %3.2f" % round(valor_obtido) | |
auxErro = saidaDesejada[i] - valor_obtido | |
#atualizando os pesos da rede | |
if (valor_obtido != saidaDesejada[i]): | |
for k in range(len(self.weights)): | |
self.weights[k] += taxa * auxErro * entrada[k][i] / 2 | |
self.bias += taxa * auxErro | |
#auxErro | |
#self.weights | |
Erro += auxErro | |
#print "Erro : %3.2f" % Erro | |
return Erro | |
#função de transferência | |
def transferencia(self,x): | |
#return 1 / (1+np.exp(-x)) | |
if x >= 0: | |
return 1 | |
else: | |
return -1 | |
def run(self, input): | |
aux = 0 | |
for i in range(len(input)): | |
aux += (self.weights[i] * input[i])+ self.bias | |
return self.transferencia(aux) | |
if __name__=='__main__': | |
neuralNet = BasicNN(2) | |
#toda vez que a rede é criada os pesos são inicializados aleatóriamente. | |
#A linha abaixo exibe os pesos com os valores iniciais. | |
print("Pesos da rede 1: %2.5f %2.5f" % (neuralNet.weights[0],neuralNet.weights[1])) | |
#entrada = np.array([[0,0],[0,1],[1,0],[1,1]]) | |
x = [0,0,1,1] | |
y = [0,1,0,1] | |
entrada = [x,y] | |
saidaDesejada = [0,0,0,1] # AND | |
#saidaDesejada = [0,1,1,1]#OR | |
taxa = 0.2 #taxa de treinamento da rede | |
taxaAux = taxa | |
for j in range(100): | |
#if j>0: | |
# taxaAux = taxa/j | |
neuralNet.treinamento(entrada, saidaDesejada, taxaAux) | |
print("Pesos da rede 2: %2.5f %2.5f" % (neuralNet.weights[0],neuralNet.weights[1])) | |
input = [1,0] | |
print("Resultado = %3.2f" % (neuralNet.run(input))) | |
plt.axis([-0.5,1.5,-0.5,1.5]) | |
#plt.plot([0,0],[0,1],'ob') | |
plt.plot(entrada[0],entrada[1],'or') | |
n = norm(neuralNet.weights) | |
ww = neuralNet.weights/n | |
ww1 = [ww[1],-ww[0]] | |
ww2 = [-ww[1],ww[0]] | |
plt.plot([ww1[0], ww2[0]],[ww1[1], ww2[1]],'--k') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment