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

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
15 [python 데이터분석] [jupyter] 주피터 노트북에 이미지 삽입 file 졸리운_곰 2025.09.06 526
14 [python 데이터분석] [Python] Streamlit 사용법 (python 데이터분석 웹 만들기) file 졸리운_곰 2024.12.22 462
13 [python 데이터분석] Anaconda : Error while loading conda entry point: conda-libmamba-solver (libarchive.so.19: cannot open shared object file: No such file or directory) 졸리운_곰 2024.12.14 520
12 [python 데이터분석] Anaconda | Conda update 반영 안됨(update 후에도 버전 변경 없음) file 졸리운_곰 2024.11.18 431
11 [python 데이터분석] Keeping Anaconda Up To Date 졸리운_곰 2024.05.30 552
10 [python 데이터 분석] 국내 경제 100대 통계지표 졸리운_곰 2024.02.18 672
9 [python 데이터 분석] Python 에서 R언어 패키지 호출 : Calling R From Python With rpy2 file 졸리운_곰 2024.01.28 676
8 [python 데이터 분석] 파이썬을 활용한 코스피, 달러 환율정보 수집부터 차트 시각화까지 file 졸리운_곰 2023.12.11 735
7 [Python 데이터분석][pandas] [Python pandas] DataFrame의 문자열 칼럼을 숫자형으로 바꾸기 : pd.to_numeric(), DataFrame.astype() file 졸리운_곰 2023.12.09 357
6 [Python 데이터분석] [Python 환경설정] VS code 설치 및 Anaconda와 연동하기 file 졸리운_곰 2023.03.17 527
5 [Python 데이터분석][python 데이터분석 프로덕션] [Python] Docker를 사용한 Dash 웹앱 생성 file 졸리운_곰 2021.12.10 403
4 [Python 데이터분석] [pandas] 공공데이터(csv) 활용시 한글 깨짐 현상 해결 file 졸리운_곰 2021.09.30 592
3 [Python 데이터분석] 공공데이터포털::공휴일 데이터 조회 (REST API) file 졸리운_곰 2021.09.30 358
2 [Python 데이터 분석] pandas의 to_csv()를 사용해서 csv 파일로 저장하기(save 하기) 졸리운_곰 2021.09.29 603
1 [Python 데이터 분석] 데이터 과학을 단순하게 만드는 3가지 Python 패키지 file 졸리운_곰 2021.09.24 513
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED