Skip to content

Instantly share code, notes, and snippets.

@arthurcvm
Created August 27, 2018 23:26
Show Gist options
  • Save arthurcvm/99f508cac28e23b520972e64f8b166c7 to your computer and use it in GitHub Desktop.
Save arthurcvm/99f508cac28e23b520972e64f8b166c7 to your computer and use it in GitHub Desktop.
Rede neural simples Adaline com regra de treinamento Delta
import xlrd
import random
import numpy as np
#https://ark4n.wordpress.com/2009/08/26/lendo-arquivos-xls-com-python/
pesos = np.array([0.0, 0.0, 0.0, 0.0])
taxaAprendizagem = 0.01
epoca = 0
entradas = 0
saidas = 0
testes = 0
for i in range(0, 4): #Ok
pesos[i] = random.uniform(0, 1) #Define os pesos como números aleatórios entre 0 e 1
print(pesos[i])
def treinamento():
global entradas
global saidas
global pesos
global epoca
global taxaAprendizagem
first = True
eqm = 0.0
eqmAnterior = 999.99
e = 10**-6
u = 0.0 #potencial de ativação
y = 0.0 #saída da rede
while((~(abs(eqm - eqmAnterior) < e)) | first): #Forçar um Do... While, Python não oferece nativamente.
first = False
if (epoca != 0):
eqmAnterior = eqm
for i in range(len(saidas)):
u = 0.0
for j in range(len(pesos)):
u += entradas[i][j] * pesos[j]
eqm = 0.0
d = saidas[i]
for j in range(len(pesos)):
pesos[j] += taxaAprendizagem * (d - u) * entradas[i][j]
eqm += pow((d - u), 2)
epoca += 1 #PERGUNTAR
print(str(epoca))
eqm = (1.0 / len(saidas)) * eqm
def xlread(arq_xls):
"""
Gerador que le arquivo .xls
"""
# Abre o arquivo
xls = xlrd.open_workbook(arq_xls)
# Pega a primeira planilha do arquivo
plan = xls.sheets()[0]
# Para i de zero ao numero de linhas da planilha
for i in range(plan.nrows):
# Le os valores nas linhas da planilha
yield plan.row_values(i)
def organizaDados():
global entradas
global saidas
for linha in xlread('treino_adaline.xlsx'):
# print(linha)
if(type(linha[0]) is float):
if(type(entradas) is int):
entradas = np.array([linha[1], linha[2], linha[3], linha[4]])
saidas = np.array([linha[5]])
else:
entrada = np.array([linha[1], linha[2], linha[3], linha[4]])
entradas = np.vstack((entradas, entrada))
saidas = np.append(saidas, linha[5])
def organizaTeste():
global testes
for linha in xlread('teste_adaline.xlsx'):
# print(linha)
if(type(linha[0]) is float):
if(type(testes) is int):
testes = np.array([linha[1], linha[2], linha[3], linha[4]])
else:
teste = np.array([linha[1], linha[2], linha[3], linha[4]])
testes = np.vstack((testes, teste))
def teste():
global pesos
global testes
u = 0.0 # potencial de ativação
y = 0.0 # saída da rede
for i in range(len(testes)):
u = 0.0
for j in range(len(testes[0])):
u += testes[i][j] * pesos[j]
if(u < 0):
y = -1
print("Amostra "+ str(i+1)+" Pertence a Classe A")
else:
y = 1
print("Amostra " + str(i + 1) + " Pertence a Classe B")
organizaDados()
organizaTeste()
print(entradas)
print(saidas)
print(testes)
treinamento()
print("Rede neural treinada")
teste()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment