Nesse primeiro artigo, estarei escrevendo sobre as Redes Neurais e algumas implementações simples desenvolvidas em Python.
Apresentando as Redes Neurais
O que são? - “São sistemas de processamento de sinais ou de informações, compostos por um grande número de processadores elementares chamados neurônios artificiais, operando de forma paralela e distribuída, de modo a resolver um determinado problema físico/computacional.”
Esquema! - (X1, X2, …, Xn) * (W1, W2, …, Wn) — F(x) — Y
Isso significa que uma Rede Neural, de um neurônio apenas, é um combinador linear que passa por uma função de ativação e dá um resultado Y, o mais interessante é que podemos programá-la para que ela dê o resultado que você deseje!
Com isso podemos fazer, dentre outras coisas, aproximadores de funções, associadores, classificação de padrões, predição futura, controle de sistemas, filtragem de sinais, compressão de dados, datamining, etc.
Redes Neurais podem ser de vários tipos, nesta parte básica vamos ver as mais simples, as Redes Neurais supervisionadas, que são treinadas (ou programadas) usando um conjunto de exemplos conhecidos, com atributos e respostas, e desta forma a Rede Neural “se acostuma” em dar os resultados desejados e passa a responder de acordo.
Programar uma Rede Neural é ajustar os valores do vetor W, de todos os neurônios, para que determinada entrada X, quando processada, resulte num valor Y desejado.
Eu irei começar com a mais simples redes neurais de todas, a Perceptron com apenas uma camada de neurônios e trabalhar sobre as diferentes arquiteturas e técnicas de aprendizado que eventualmente irão convergir para redes que podem prever tendências dos preços das ações de uma bolsa de valores, reconhecimento de padrões, processamento de linguagem natural, etc.
O Perceptron é o ancião de todas as redes neurais. Ela foi criada em 1957 nos laboratórios das forças militares por Frank Rosenblatt. O Perceptron é o mais simples tipo de rede neural diretas (Feedfoward) , conhecido como classificador linear. Isto significa que os tipos de problemas solucionados por esta rede neural devem ser linearmente separáveis. O que significa isso ? O gráfico abaixo ilustra facilmente o que ser um problema linearmente/não-linearmente separáveis em duas dimensões.
Lineamente Separável. | Não linearmente separável. |
A linha verde representa a separação entre duas classes de dados que uma rede está tentando classificar. Em três dimensões, isto seria representado por um plano, e em 4 dimensões ou mais por um hiper-plano. Há outros tipos de redes de neurais que pdoem solucionar problemas linearmente e não linearmente separáveis, que serão discutidas em futuros posts.
Para tentar resolver este problema, nós precisamos de uma rede representada pela figura abaixo.
Como vocês podem observar, cada nó de entrada (input) está diretamente conectado ao nó de saída (output). Ajustando os valores dos pesos (weight) que conectam tais nós , a rede é capaz de aprender.
Em uma simples demonstração, irei usar o conjunto de dados plotados no primeiro gráfico aqui apresentado como os dados de treinamento (conjunto de dados para treinamento). O conjunto de dados de treinamento será usado repetidamente como entrada para os nós de entrada (input) da rede neural, fazendo com que os pesos se ajustem até a rede neural atinja o desempenho e objetivo desejado, que é classificar um conjunto de dados linearmente separáveis.
Uma vez que a rede neural foi treinada, a aplicação irá acessar uma base de dados (diferente dos dados de treinamento) e irá provar que a rede neural aprendeu corretamente e tem a capacidade de generalização; ela pode encontrar respostas corretas mesmos quandos os dados de entrada estão incompletos ou quando a relação entre a entrada e a saída não é concreta.
O código abaixo mostra como isso foi realizado.
Um algoritmo simples
Este descreve apenas o funcionamento de um neurônio.
##################################################
# #
# Copyright 2008 Marcel Pinheiro Caraciolo #
# #
# #
# -- Perceptron Neural Net snippet code #
# -- Version: 0.1 - 12/12/2008 #
##################################################
#Snippet Neuron
from random import random
class Neuron:
def __init__(self,data,learningRate = 0.1):
self._learning_rate = learningRate
self._input,self._output = data
#Randomise weights.
self._weight = map(lambda x: x*random(), [1] * len(self._input))
#print self._weight
self._y = None
self._global_error = 0.0
def train(self,data):
self._input,self._output = data
#Calculate output.
self._y = self._sign(self._sum())
#Calculate error.
if self._error() != 0:
#Update weights.
self._adjustWeight()
#Convert error to absolute value.
self._global_error += abs(self._error())
def execute(self,input):
self._input = input
#Calculate output.
self._y = self._sign(self._sum())
return self._y
def _sum(self):
return sum(map(lambda x,y: x*y, self._input,self._weight))
def _sign(self,output):
if output < 0:
y = -1
else:
y = 1
return y
def _error(self):
return self._output - self._y
def _adjustWeight(self):
self._weight = map(lambda x,y: x + (y*self._learning_rate*self._error()),self._weight,self._input)
def getGlobalError(self):
return self._global_error
def resetGlobalError(self):
self._global_error = 0
E para executar o perceptron, que é o que irá apresentar os exemplos ao neurônio, temos:
##################################################
# #
# Copyright 2008 -Marcel Pinheiro Caraciolo- #
# #
# #
# -- Perceptron Neural Net snippet code #
# -- Version: 0.1 - 12/12/2008 #
##################################################
#Snippet Perceptron
from Neuron import *
class Perceptron:
def __init__(self,inputs,iterations=100):
self._inputs = inputs
self._refresh_inputs = list(inputs)
self._iterations = iterations
self._iteration = 0
self._neuron = Neuron(self._getRandInput())
self._train()
def _train(self):
while self._iteration <= self._iterations:
self._neuron.resetGlobalError()
self._refresh_inputs = list(self._inputs)
for i in range(len(self._refresh_inputs)):
self._neuron.train(self._getRandInput())
print "Iteration %d Error: %f" % (self._iteration, self._neuron.getGlobalError())
self._iteration += 1
if(self._neuron.getGlobalError() == 0.0):
break
def _getRandInput(self):
return self._refresh_inputs.pop()
def execute(self,input):
return self._neuron.execute(input)
def arange(self,start,stop=None,step=None):
if stop is None:
stop = float(start)
start = 0.0
if step is None:
step = 1.0
cur = float(start)
while cur <= stop:
yield cur
cur+=step
Execute as classes acima usando:
#main Logic
#Load sample input patterns
inputs = [ [[0.72, 0.82], -1], [[0.91, -0.69], -1],
[[0.46, 0.80], -1], [[0.03, 0.93], -1],
[[0.12, 0.25], -1], [[0.96, 0.47], -1],
[[0.8, -0.75], -1], [[0.46, 0.98], -1],
[[0.66, 0.24], -1], [[0.72, -0.15], -1],
[[0.35, 0.01], -1], [[-0.16, 0.84], -1],
[[-0.04, 0.68], -1], [[-0.11, 0.1], 1],
[[0.31, -0.96], 1], [[0.0, -0.26], 1],
[[-0.43, -0.65], 1], [[0.57, -0.97], 1],
[[-0.47, -0.03], 1], [[-0.72, -0.64], 1],
[[-0.57, 0.15], 1], [[-0.25, -0.43], 1],
[[0.47, -0.88], 1], [[-0.12, -0.9], 1],
[[-0.58, 0.62], 1], [[-0.48, 0.05], 1],
[[-0.79, -0.92], 1], [[-0.42, -0.09], 1],
[[-0.76, 0.65], 1], [[-0.77, -0.76], 1]]
perceptron = Perceptron(inputs,1000)
#Display network generalization
print ""
print "X, Y, Output"
for i in perceptron.arange(-1,1,0.5):
for j in perceptron.arange(-1,1,0.5):
#Calculate output.
result = perceptron.execute(list((i,j)))
if result == 1:
result = "Blue"
else:
result = "Red"
print "%f %f %s" % (i,j,result)
A saída da rede após o treinamento é exibida conforme abaixo, o que prova que a generalização foi atingida. Cada par de coordenadas (x,y) quando apresentadas à rede, retorna a classificação esperada, isto é, vermelho ou azul.
(...)
X, Y, Output
-1.000000 -1.000000 Blue
-1.000000 -0.500000 Blue
-1.000000 0.000000 Blue
-1.000000 0.500000 Blue
-1.000000 1.000000 Blue
-0.500000 -1.000000 Blue
-0.500000 -0.500000 Blue
-0.500000 0.000000 Blue
-0.500000 0.500000 Blue
-0.500000 1.000000 Red
0.000000 -1.000000 Blue
0.000000 -0.500000 Blue
0.000000 0.000000 Blue
0.000000 0.500000 Red
0.000000 1.000000 Red
0.500000 -1.000000 Blue
0.500000 -0.500000 Red
0.500000 0.000000 Red
0.500000 0.500000 Red
0.500000 1.000000 Red
1.000000 -1.000000 Red
1.000000 -0.500000 Red
1.000000 0.000000 Red
1.000000 0.500000 Red
1.000000 1.000000 Red
Analise o objeto criado, seus métodos e pesos, verifique que com o método “execute” você poderá testar se as respostas estão sendo dadas corretamente.
Além de problemas triviais como este de classificação de 2 dimensões , o Perceptron pode realizar uma análise mais poderosa em mais dimensões. As regras genéricas aqui apresentadas são também aplicáveis.
No próximo post, eu falarei mais sobre a Adaline, que é outro tipo de rede neural feedfoward como o Perceptron.
Download dos códigos aqui.
Parabéns ótimo tópico :D
ReplyDeletePena, para mim, que eu não entendo Python e tenho que suar pra entender o código >.<
Parabéns !!
ReplyDeleteMuito bom ! Vou adaptalo para Delphi.
Vlw.
Muito Bom!!!
ReplyDeleteMe ajudou muito Marcel!
Abs,
Fabíola
não tem como baixar os códigos se possível manda pro meu email andreferreiraesilva@gmail.com
ReplyDeletechupa minha pica
ReplyDeletemuito bom material !!
ReplyDeleteRealmente bem legal, vou testar os códigos posteriormente.
ReplyDeleteO download do .zip está com problema.
o link pra download dos codigos não aponta para o local certo...
ReplyDelete:-(
PLC training in Cochin, Kerala
ReplyDeleteAutomation training in Cochin, Kerala
Embedded System training in Cochin, Kerala
VLSI training in Cochin, Kerala
PLC training institute in Cochin, Kerala
Embedded training in Cochin, Kerala
Best plc training in Cochin, Kerala
It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end.
ReplyDeleteAWS Training in Bangalore
Python Training in Bangalore
corporate training companies
ReplyDeletecorporate training companies in mumbai
corporate training companies in pune
corporate training companies in delhi
corporate training companies in chennai
corporate training companies in hyderabad
corporate training companies in bangalore
Gaining Python certifications will validate your skills and advance your career.
ReplyDeletepython certification
Needed to compose one simple word yet thanks for the suggestions that you are contributed here, please do keep updating us...
ReplyDeleteArtificial Intelligence Training | Automation Anywhere Online Training
I am glad to read your blog this is very interesting & informative.
ReplyDeleteMicroservices Online Training
I just see the post i am so happy the post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be subscribing to your feed and I hope you post again soon.
ReplyDeletebest selenium training institute in hyderabad
Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this. Well written article
ReplyDeleteMachine Learning With TensorFlow Training and Course in Tel Aviv
| CPHQ Online Training in Beirut. Get Certified Online
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeleteartificial intelligence training in hyderabad
Nice Article.Really enjoyed while reading this article.
ReplyDeletepython course in bangalore
This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
ReplyDelete
ReplyDeleteAmazing content.
Data Mining Service Providers in Bangalore
I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
ReplyDeleteblog page
ReplyDeleteThanks for sharingData Mining software service providers
Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. I would like to state about something which creates curiosity in knowing more about it. It is a part of our daily routine life which we usually don`t notice in all the things which turns the dreams in to real experiences. Back from the ages, we have been growing and world is evolving at a pace lying on the shoulder of technology."data science courses" will be a great piece added to the term technology. Cheer for more ideas & innovation which are part of evolution.
ReplyDeleteAttend The PMP in Bangalore From ExcelR. Practical PMP in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The PMP in Bangalore.
ReplyDeleteExcelR PMP in Bangalore
It is a very awesome post and truly good effort. I really appreciate your useful blog...
ReplyDeleteLinux Training in Chennai
Learn Linux
Spark Training in Chennai
Oracle Training in Chennai
JMeter Training in Chennai
Tableau Training in Chennai
Appium Training in Chennai
Power BI Training in Chennai
Embedded System Course Chennai
Pega Training in Chennai
I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
ReplyDelete360digitmg Data Science Course
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
ReplyDeleteExcelR Data Analytics Course
Data Science Interview Questions
nice post...
ReplyDeleteinternship report on python
free internship in chennai for ece students
free internship for bca
internship for computer science engineering students in india
internships in hyderabad for cse students 2018
electrical companies in hyderabad for internship
internships in chennai for cse students 2019
internships for ece students
inplant training in tcs chennai
internship at chennai
good... nice... very useful..
ReplyDeleteassistant-director-resume-format
director-resume-sample
assistant-professor-resume-sample
back-office-executive-resume-samples
bank-branch-manager-resume-samples
basketball-coach-resume-sample-coach-resumes
bca-fresher-resume-sample
best-general-manager-resume-example
bpo-resume-freshers-sample
bpo-resume-samples-for-freshers
useful information..nice..
ReplyDeletedevops-engineer-resume-samples
digital-marketing-resume-samples
digital-marketing-resume-samples
electronics-engineer-resume-sample
engineering-lab-technician-resume-samples
english-teacher-cv-sample
english-teacher-resume-example
english-teacher-resume-sample
excel-expert-resume-sample
executive-secretary-resume-samples
NearLearn is one of the best institutes in Bangalore which provides professional and short term term trainibng on different courses at affordable prices
ReplyDeletebest React JS Training course in Bangalore
Blockchain training in Bangalore
python certification training course in Bangalore
ReplyDeleteAwesome blog. I enjoyed reading your articles.
Cyber security course
After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article
ReplyDeletecyber security course
Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.
ReplyDeletedata science courses
Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here...artificial intelligence course in bangalore
ReplyDeleteExcellent article. I want to thank you for this informative read; I really appreciate sharing this great post. Keep up your work!
ReplyDeletedigital marketing course in chennai, digital marketing training in chennai, best digital marketing, digital marketing, skartec digital marketing, skartec digital marketing academy, seo training in chennai, best seo service in chennai, digital marketing blog
This comment has been removed by the author.
ReplyDeleteI have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…
ReplyDeleteData Science Courses Super site! I am Loving it!! Will return once more, Im taking your food likewise, Thanks.
python training in bangalore | python online training
ReplyDeleteaws training in bangalore | aws online training
artificial intelligence training in bangalore | artificial intelligence online training
machine learning training in bangalore | machine learning online training
blockchain training in bangalore | blockchain online training
uipath training in bangalore | uipath online training
Amazing post found to be very impressive while going through this post. Thanks for sharing and keep posting such an informative content.
ReplyDelete360DigiTMG Cloud Computing Course
https://www.happierit.com
ReplyDeletehttps://www.happierit.com
https://www.happierit.com
https://www.happierit.com
https://www.happierit.com
https://www.happierit.com
https://www.happierit.com
https://www.happierit.com
I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
ReplyDeleteData Analytics Course Pune wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person in some of them hope you will give more information on this topics in your next articles.
I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
This professional hacker is absolutely reliable and I strongly recommend him for any type of hack you require. I know this because I have hired him severally for various hacks and he has never disappointed me nor any of my friends who have hired him too, he can help you with any of the following hacks:
ReplyDelete-Phone hacks (remotely)
-Credit repair
-Bitcoin recovery (any cryptocurrency)
-Make money from home (USA only)
-Social media hacks
-Website hacks
-Erase criminal records (USA & Canada only)
-Grade change
-funds recovery
Email: onlineghosthacker247@ gmail .com
Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
ReplyDeleteBest Digital Marketing Courses in Hyderabad
ReplyDeleteTook me time to understand all of the comments, but I seriously enjoyed the write-up. It proved being really helpful to me and Im positive to all of the commenters right here! Its constantly nice when you can not only be informed, but also entertained! I am certain you had enjoyable writing this write-up.
artificial intelligence course in bangalore
Amazing web journal. I appreciated perusing your articles. This is really an incredible perused for me.
ReplyDeleteSEO Training in Hyderabad
I see some amazingly important and kept up to length of your strength searching for in your on the site
ReplyDeletedata scientists training
Digital marketing coaching in hyderabad
ReplyDeleteDigital Marketing Training in KPHB at digital brolly
ReplyDeleteDigital Marketing Training in KPHB at Digital Brolly
ReplyDeleteGreat Information, thanks for sharing..
ReplyDeleteSocial Media Marketing Course
Digital Marketing Career Aspirants
ReplyDeleteYou could be a student or a fresher just out of college or a working professional that wants to shift their career into Digital Marketing can attend this digital marketing course
Awesome blog post, thanks for sharing.
ReplyDeleteSEO Training In Hyderabad
Social Media Marketing Course (SMM) In Hyderabad
ReplyDeleteClass RoomOnline2 Weeks8,000 RsRs. 6000/-
Register now to participate in the intensive AI Course in Hyderabad program taught by experts at the AI Patasala training center.
ReplyDeleteHey!! This is such an amazing article that I have read today & you don't believe that I have enjoyed a lot while reading this amazing article. thanx for sharing such an amazing article with us. SEO Company in Hyderabad
ReplyDeleteInformative blog. Thanks for sharing with us. Join us today to participate in the special Machine Learning Course in Hyderabad program led by AI Patasala.
ReplyDeleteMachine Learning Training Hyderabad
Perfect blog to read in free time to gain knowladge.https://louisomjg44455.blogspothub.com/7253239/all-about-satta-king
ReplyDeleteJoin for the top Artificial Intelligence Training in Hyderabad. In AI Patasala, aspirants can avail the benefits of demonstration sessions of the AI Program.
ReplyDeleteArtificial Intelligence Course
ReplyDeleteThe blog and data is excellent and informative as well
data science course in malaysia
Really an awesome blog and informative content. Keep posting more blogs with us. Thank you.
ReplyDeleteData Science Course in Hyderabad
This is a very nice post you shared, I like the post, thanks for sharing.
ReplyDeletecyber security certification malaysia
You completed certain reliable points there. I did a search on the subject and found nearly all persons will agree with your blog.data science training in jabalpur
ReplyDeleteYour content is very unique and understandable useful for the readers keep update more article like this...
ReplyDeleteYoutube training in hyderabad
Hairextensionscottsdale guarantees best micro ring hair extension at most cost-effective prices available on the market Micro Ring Hair Extensions Scottsdale Visit today!
ReplyDeleteAre you looking to buy or sell a home in Okotoks, Calgary? If you want to sell it fast and get the best price possible then it is important that you find a really Best realtors in Okotoks that knows what they are doing. Check out our site for more information. https://www.mattburnham.com
ReplyDeleteEste artigo provavelmente aborda a introdução às redes neurais e ao conceito de Perceptron. É uma leitura valiosa para quem deseja entender os fundamentos das redes neurais e como o Perceptron se encaixa nesse contexto.
ReplyDeleteData Analytics Courses In Kochi
Hello Blogger,
ReplyDeleteThis article provides a clear introduction to neural networks and the Perceptron, offering valuable insights for those interested in understanding the fundamentals of artificial neural networks. The provided code examples add practicality to the explanation, making it an excellent resource for beginners in the field.
Data Analytics Courses In Dubai
Thank you for simplifying complex concepts and making them more understandable to those eager to learn about neural networks and their significance in the tech world!
ReplyDeleteData Analytics Courses In Chennai
I appreciate your efforts to clarify complex ideas for anyone curious about neural networks and their importance in the tech industry.
ReplyDeleteData Analytics Courses in Agra
This comment has been removed by the author.
ReplyDeleteIt’s an amazing post for all the web visitors; they will
ReplyDeletetake benefit from it I am sure. Also check : best clinic management software , best employee engagement software.
The way you break down these complex concepts into understandable pieces is commendable.
ReplyDeleteDigital marketing courses in illinois
thanks for sharing such insightfully written blog post, really well written
ReplyDeleteDigital marketing business
Beautiful blog post. This was some useful stuff.
ReplyDeleteInvestment banking analyst jobs
Very nice blogs!!! I have to learn for lot of information for this site…Sharing wonderful information.
ReplyDeleteData analytics framework
AI is the future and we may expect spectacular breakthroughs in all aspects governing our lifestyle.
ReplyDeleteInvestment banking courses after 12th
Data Science Course in Indore
ReplyDeleteWelcome to iTech Manthra, your premier destination for top-notch seo training in hyderabad
ReplyDelete! We specialize in providing comprehensive courses that o
iTech Manthra offers some of the best SEO training in Hyderabad! The trainers are incredibly knowledgeable, and the hands-on approach really helps students grasp the complexities of SEO. I especially liked how they focus on both foundational and advanced techniques, making it suitable for beginners and experienced professionals alike. While researching training institutes, I also came across Digital Brolly, which also offers great SEO courses. Both iTech Manthra and Digital Brolly seem like fantastic places to learn and grow in the digital marketing field. Keep up the excellent work
ReplyDeleteSEO Training in Hyderabad
This blog consistently provides valuable insights and updates on the latest advancements in data science..data science classes in chennai
ReplyDelete