How to build a simple neural network in 9 lines of Python code

 

As part of my quest to learn about AI, I set myself the goal of building a simple neural network in Python. To ensure I truly understand it, I had to build it from scratch without using a neural network library. Thanks to an excellent blog post by Andrew Trask I achieved my goal. Here it is in just 9 lines of code:

 

In this blog post, I’ll explain how I did it, so you can build your own. I’ll also provide a longer, but more beautiful version of the source code.

But first, what is a neural network? The human brain consists of 100 billion cells called neurons, connected together by synapses. If sufficient synaptic inputs to a neuron fire, that neuron will also fire. We call this process “thinking”.

 
Diagram 1

We can model this process by creating a neural network on a computer. It’s not necessary to model the biological complexity of the human brain at a molecular level, just its higher level rules. We use a mathematical technique called matrices, which are grids of numbers. To make it really simple, we will just model a single neuron, with three inputs and one output.

We’re going to train the neuron to solve the problem below. The first four examples are called a training set. Can you work out the pattern? Should the ‘?’ be 0 or 1?

 
Diagram 2

You might have noticed, that the output is always equal to the value of the leftmost input column. Therefore the answer is the ‘?’ should be 1.

Training process

But how do we teach our neuron to answer the question correctly? We will give each input a weight, which can be a positive or negative number. An input with a large positive weight or a large negative weight, will have a strong effect on the neuron’s output. Before we start, we set each weight to a random number. Then we begin the training process:

  1. Take the inputs from a training set example, adjust them by the weights, and pass them through a special formula to calculate the neuron’s output.
  2. Calculate the error, which is the difference between the neuron’s output and the desired output in the training set example.
  3. Depending on the direction of the error, adjust the weights slightly.
  4. Repeat this process 10, 000 times.
 
Diagram 3

Eventually the weights of the neuron will reach an optimum for the training set. If we allow the neuron to think about a new situation, that follows the same pattern, it should make a good prediction.

This process is called back propagation.

Formula for calculating the neuron’s output

You might be wondering, what is the special formula for calculating the neuron’s output? First we take the weighted sum of the neuron’s inputs, which is:

 

Next we normalise this, so the result is between 0 and 1. For this, we use a mathematically convenient function, called the Sigmoid function:

 

If plotted on a graph, the Sigmoid function draws an S shaped curve.

 
Diagram 4

So by substituting the first equation into the second, the final formula for the output of the neuron is:

 

You might have noticed that we’re not using a minimum firing threshold, to keep things simple.

Formula for adjusting the weights

During the training cycle (Diagram 3), we adjust the weights. But how much do we adjust the weights by? We can use the “Error Weighted Derivative” formula:

 

Why this formula? First we want to make the adjustment proportional to the size of the error. Secondly, we multiply by the input, which is either a 0 or a 1. If the input is 0, the weight isn’t adjusted. Finally, we multiply by the gradient of the Sigmoid curve (Diagram 4). To understand this last one, consider that:

  1. We used the Sigmoid curve to calculate the output of the neuron.
  2. If the output is a large positive or negative number, it signifies the neuron was quite confident one way or another.
  3. From Diagram 4, we can see that at large numbers, the Sigmoid curve has a shallow gradient.
  4. If the neuron is confident that the existing weight is correct, it doesn’t want to adjust it very much. Multiplying by the Sigmoid curve gradient achieves this.

The gradient of the Sigmoid curve, can be found by taking the derivative:

 

So by substituting the second equation into the first equation, the final formula for adjusting the weights is:

 

There are alternative formulae, which would allow the neuron to learn more quickly, but this one has the advantage of being fairly simple.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Constructing the Python code

Although we won’t use a neural network library, we will import four methods from a Python mathematics library called numpy. These are:

  • exp — the natural exponential
  • array — creates a matrix
  • dot — multiplies matrices
  • random — gives us random numbers

For example we can use the array() method to represent the training set shown earlier:

 

The ‘.T’ function, transposes the matrix from horizontal to vertical. So the computer is storing the numbers like this.

 

Ok. I think we’re ready for the more beautiful version of the source code. Once I’ve given it to you, I’ll conclude with some final thoughts.

I have added comments to my source code to explain everything, line by line. Note that in each iteration we process the entire training set simultaneously. Therefore our variables are matrices, which are grids of numbers. Here is a complete working example written in Python:

 

Also available here: https://github.com/miloharper/simple-neural-network

Final thoughts

Try running the neural network using this Terminal command:

python main.py

You should get a result that looks like:

 

We did it! We built a simple neural network using Python!

First the neural network assigned itself random weights, then trained itself using the training set. Then it considered a new situation [1, 0, 0] and predicted 0.99993704. The correct answer was 1. So very close!

Traditional computer programs normally can’t learn. What’s amazing about neural networks is that they can learn, adapt and respond to new situations. Just like the human mind.

Of course that was just 1 neuron performing a very simple task. But what if we hooked millions of these neurons together? Could we one day create something conscious?

I’ve been inspired by the huge response this article has received. I’m considering creating an online course.

 

[출처] https://medium.com/technology-invention-and-more/how-to-build-a-simple-neural-network-in-9-lines-of-python-code-cc8f23647ca1

[참고] https://www.youtube.com/watch?v=h3l4qz76JhQ

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
38 [flask] wsgi를 이용한 Apache httpd 연동 file 졸리운_곰 2019.12.07 433
37 파이썬 플라스크 프레임워크 소개 졸리운_곰 2018.08.03 532
36 The Ultimate Flask Front-End – Part 2 file 졸리운_곰 2018.06.22 452
35 The Ultimate Flask Front-End file 졸리운_곰 2018.06.22 390
34 Flask-RESTPlus에서 REST API와 Swagger 문서를 통합 file 졸리운_곰 2018.05.22 722
33 Building beautiful REST APIs using Flask, Swagger UI and Flask-RESTPlus file 졸리운_곰 2018.05.22 747
32 [Python] Flask & flask-restplus && swagger ui file 졸리운_곰 2018.05.22 414
31 How to deploy python-flask in wampserver file 졸리운_곰 2018.02.14 367
30 The Ultimate Flask Front-End - Part 2 file 졸리운_곰 2017.10.06 841
29 The Ultimate Flask Front-End file 졸리운_곰 2017.10.06 464
28 Create a scikit-learn based prediction webapp using Flask and Heroku file 졸리운_곰 2017.08.22 454
27 How to deploy python-flask in wampserver file 졸리운_곰 2017.07.22 529
26 Welcome to Flask-MySQLdb’s documentation! 졸리운_곰 2017.07.22 352
25 Flask에서 SQLAlchemy 사용하기 졸리운_곰 2017.07.22 502
24 Flask에서 SQLite 3 사용하기 졸리운_곰 2017.07.22 623
23 How To Set Up an Apache, MySQL, and Python (LAMP) Server Without Frameworks on Ubuntu 14.04 졸리운_곰 2017.07.22 462
22 flask-simple-image-gallery 가을의곰 2017.06.10 453
21 Flask Quick Start, 플라스크 빠르게 해보기 졸리운_곰 2017.05.01 416
20 Application Skeleton for Flask and AngularJS file 졸리운_곰 2017.02.06 596
19 Flask by Example - Integrating Flask and Angular file 졸리운_곰 2017.02.06 1002
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED