SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
오류 역전파 알고리즘 구현
딥러닝을 위한 신경망 기초
nonezerok@gmail.com
프로그램 코드를 통해 오류역전파알고리즘에 대한 이해를 높일 수 있습니다.
여기서 제시되는 C 코드는 오류역전파알고리즘을 이해하는 데 목적을 두어 최대한 간결하게 작성되어 있습니다.
또한 Tensorflow 코드로 제공된 필기체 숫자인식을 통해 실제 사례에 어떻게 적용되는지를 살펴볼 수 있습니다.
신경망은 주어진 데이터에 따라 학습자가 조정해야 할 값들이 있습니다.
이 값들을 변경해 보면서 조정값들에 대한 경험치를 쌓는데 본 코드를 활용할 수 있습니다.
2
MLP for XOR pattern
in C
3
 =
1
1
 = 1
 =
0
1
 = 0
 =
0
0
 = 0
 =
1
0
 = 0
Input Layer Hidden Layer Output Layer
1 1
Net0
Net1
Net2
0
1
2
w00
w10
w11
w21
w20
w02
0
w12
w22
x1
x2
y
w01
Weight[3][3]
out
포물선으로 구분
4
/* ========================================== *
* Filename: bpnet.h
* Author: James Matthews.
* This is a tiny neural network that uses
* back propagation for weight adjustment.
* ========================================== */
#define BP_LEARNING(float)(0.5)// The learning coefficient.
class CBPNet{
public:
CBPNet();
~CBPNet() {};
float Train(float, float, float);
float Run(float, float);
private:
float m_fWeights[3][3];// Weights for the 3 neurons.
float Sigmoid(float);// The sigmoid function.
};
5
CBPNet::CBPNet()
{
srand((unsigned)(time(NULL)));
for (inti=0;i<3;i++) {
for (intj=0;j<3;j++) {
m_fWeights[i][j] = (float)(rand())/(32767/2) -1;
}
}
}
6
float CBPNet::Train(floati1, float i2, float y)
{
float net1, net2, i3, i4, out;
net1 = 1*m_fWeights[0][0]+i1*m_fWeights[1][0]+i2*m_fWeights[2][0];
net2 = 1*m_fWeights[0][1]+i1*m_fWeights[1][1]+i2*m_fWeights[2][1];
i3 = Sigmoid(net1);
i4 = Sigmoid(net2);
net1 = 1*m_fWeights[0][2]+i3*m_fWeights[1][2]+i4*m_fWeights[2][2];
out = Sigmoid(net1);
7
float deltas[3];
deltas[2] = out*(1-out)*(y-out);
deltas[1] = i4*(1-i4)*(m_fWeights[2][2])*(deltas[2]);
deltas[0] = i3*(1-i3)*(m_fWeights[1][2])*(deltas[2]);
 ←  1 −   − 
 ←  1 −   ,


Input Layer Hidden Layer Output Layer
1 1
Net0
Net1
Net2
0
1
2
w00
w10
w11
w21
w20
w02
0
w12
w22
x1
x2
y
w01
Weight[3][3]
out
float v1 = i1, v2 = i2;
for(int i=0;i<3;i++) {
// Change the values for the output layer, if necessary.
if (i == 2) {
v1 = i3;
v2 = i4;
}
m_fWeights[0][i] += BP_LEARNING*1*deltas[i];
m_fWeights[1][i] += BP_LEARNING*v1*deltas[i];
m_fWeights[2][i] += BP_LEARNING*v2*deltas[i];
}
return out;
}
, ← , + ∆,
∆, = 
 =  when  is of the first layer
9
float CBPNet::Sigmoid(floatnum)
{
return (float)(1/(1+exp(-num)));
}
float CBPNet::Run(floati1, float i2)
{
float net1, net2, i3, i4;
net1 = 1*m_fWeights[0][0]+i1*m_fWeights[1][0]+i2*m_fWeights[2][0];
net2 = 1*m_fWeights[0][1]+i1*m_fWeights[1][1]+i2*m_fWeights[2][1];
i3 = Sigmoid(net1);
i4 = Sigmoid(net2);
net1 = 1*m_fWeights[0][2]+i3*m_fWeights[1][2]+i4*m_fWeights[2][2];
return Sigmoid(net1);
}
10
#define BPM_ITER2000
void main()
{
CBPNet bp;
for (inti=0;i<BPM_ITER;i++) {
bp.Train(0,0,0);
bp.Train(0,1,1);
bp.Train(1,0,1);
bp.Train(1,1,0);
}
cout<< "0,0 = " << bp.Run(0,0) << endl;
cout<< "0,1 = " << bp.Run(0,1) << endl;
cout<< "1,0 = " << bp.Run(1,0) << endl;
cout<< "1,1 = " << bp.Run(1,1) << endl;
}
11
1 1
Net0
Net1
Net2
0
1
2
w00
w10
w11
w21
w20
w02
0
w12
w22
x1
x2
y1
w01
out
Net3 y2
out
출력 층의 노드를 2개로 확장 구현 스스로!
12
MLP on MNIST
in Tensorflow
13
http://yann.lecun.com/exdb/mnist/
28
28
28X28=768
• 5,5000개 학습 데이터
• 10,000개 테스트 데이터
MNIST
14
https://ml4a.github.io/ml4a/neural_networks/
0~1사이로 변경 후 입력
15
3 layers perceptron
https://ml4a.github.io/demos/forward_pass_mnist/
8번 뉴런 (노드)에서 가장
큰 값을 출력
8과 유사한 것 중 하나
16
'
' https://github.com/rickiepark/tfk-notebooks
'
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
plt.imshow(mnist.train.images[100].reshape([28, 28]),
cmap=plt.get_cmap('gray_r'))
x = tf.placeholder("float32", [None, 784])
y = tf.placeholder("float32", shape=[None, 10])
W1 = tf.Variable(tf.truncated_normal([784, 100], stddev=0.1))
b1 = tf.Variable(tf.constant(0.1, shape=[100]))
17
t = tf.sigmoid(tf.matmul(x,W1) + b1)
W2 = tf.Variable(tf.truncated_normal([100, 10], stddev=0.1))
b2 = tf.Variable(tf.constant(0.1, shape=[10]))
z = tf.matmul(t,W2) + b2
y_hat = tf.nn.softmax(z)
loss = tf.losses.softmax_cross_entropy(y, z)
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_hat,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
18
costs = []
for i in range(1000):
x_data, y_data = mnist.train.next_batch(100)
_, cost = sess.run([train, loss], feed_dict={x: x_data, y: y_data})
costs.append(cost)
plt.plot(costs)
for i in range(5):
plt.imshow(mnist.test.images[i].reshape([28, 28]),
cmap=plt.get_cmap('gray_r'))
plt.show()
print(sess.run(tf.argmax(y_hat,1),
feed_dict={x: mnist.test.images[i].reshape([1,784])}))

Weitere ähnliche Inhalte

Was ist angesagt?

TensorFlow Tutorial
TensorFlow TutorialTensorFlow Tutorial
TensorFlow TutorialNamHyuk Ahn
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMohammad Usman
 
Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis Bharti Airtel Ltd.
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Khor SoonHin
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowKhor SoonHin
 
30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature SelectionJames Huang
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code GolfYelp Engineering
 
The Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorThe Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorAbhranil Das
 
2018 06-19 paris cybersecurity meetup
2018 06-19 paris cybersecurity meetup2018 06-19 paris cybersecurity meetup
2018 06-19 paris cybersecurity meetupRaphaël Laffitte
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practiceindico data
 
Statistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetStatistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetLaurel Ayuyao
 
Kristhyan kurtlazartezubia evidencia1-metodosnumericos
Kristhyan kurtlazartezubia evidencia1-metodosnumericosKristhyan kurtlazartezubia evidencia1-metodosnumericos
Kristhyan kurtlazartezubia evidencia1-metodosnumericosKristhyanAndreeKurtL
 

Was ist angesagt? (20)

TensorFlow Tutorial
TensorFlow TutorialTensorFlow Tutorial
TensorFlow Tutorial
 
Lec 3-mcgregor
Lec 3-mcgregorLec 3-mcgregor
Lec 3-mcgregor
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
 
Numerical methods generating polynomial
Numerical methods generating polynomialNumerical methods generating polynomial
Numerical methods generating polynomial
 
30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection30 分鐘學會實作 Python Feature Selection
30 分鐘學會實作 Python Feature Selection
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code Golf
 
Matlab differential
Matlab differentialMatlab differential
Matlab differential
 
The Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorThe Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
 
2018 06-19 paris cybersecurity meetup
2018 06-19 paris cybersecurity meetup2018 06-19 paris cybersecurity meetup
2018 06-19 paris cybersecurity meetup
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
R - binomial distribution
R - binomial distributionR - binomial distribution
R - binomial distribution
 
Langrange method for MATLAB Code
Langrange method for MATLAB CodeLangrange method for MATLAB Code
Langrange method for MATLAB Code
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
 
Codecomparaison
CodecomparaisonCodecomparaison
Codecomparaison
 
Statistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat SheetStatistics for Economics Midterm 2 Cheat Sheet
Statistics for Economics Midterm 2 Cheat Sheet
 
Kristhyan kurtlazartezubia evidencia1-metodosnumericos
Kristhyan kurtlazartezubia evidencia1-metodosnumericosKristhyan kurtlazartezubia evidencia1-metodosnumericos
Kristhyan kurtlazartezubia evidencia1-metodosnumericos
 
Procedural Art
Procedural ArtProcedural Art
Procedural Art
 

Ähnlich wie [신경망기초]오류역전파알고리즘구현

PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...Andrey Karpov
 
Matlab practical file
Matlab practical fileMatlab practical file
Matlab practical fileArchita Misra
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionAndrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionPVS-Studio
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questionsGradeup
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
C and data structure
C and data structureC and data structure
C and data structureprabhatjon
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploitsPriyanka Aash
 
Aosd2009 adams
Aosd2009 adamsAosd2009 adams
Aosd2009 adamsSAIL_QU
 
openMP loop parallelization
openMP loop parallelizationopenMP loop parallelization
openMP loop parallelizationAlbert DeFusco
 
Sample presentation slides template
Sample presentation slides templateSample presentation slides template
Sample presentation slides templateValerii Klymchuk
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...David Walker
 

Ähnlich wie [신경망기초]오류역전파알고리즘구현 (20)

Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
White box-sol
White box-solWhite box-sol
White box-sol
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
Matlab practical file
Matlab practical fileMatlab practical file
Matlab practical file
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Tutorial 2
Tutorial     2Tutorial     2
Tutorial 2
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
C and data structure
C and data structureC and data structure
C and data structure
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
 
Aosd2009 adams
Aosd2009 adamsAosd2009 adams
Aosd2009 adams
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
openMP loop parallelization
openMP loop parallelizationopenMP loop parallelization
openMP loop parallelization
 
Sample presentation slides template
Sample presentation slides templateSample presentation slides template
Sample presentation slides template
 
C語言函式
C語言函式C語言函式
C語言函式
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
 
Staging driver sins
Staging driver sinsStaging driver sins
Staging driver sins
 

Mehr von jaypi Ko

CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Model
CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic ModelCVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Model
CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Modeljaypi Ko
 
개념 이해가 쉬운 Variational Autoencoder (VAE)
개념 이해가 쉬운 Variational Autoencoder (VAE)개념 이해가 쉬운 Variational Autoencoder (VAE)
개념 이해가 쉬운 Variational Autoencoder (VAE)jaypi Ko
 
파이썬설치
파이썬설치파이썬설치
파이썬설치jaypi Ko
 
객체지향 단어가 의미하는 것
객체지향 단어가 의미하는 것객체지향 단어가 의미하는 것
객체지향 단어가 의미하는 것jaypi Ko
 
C언어 들어가기
C언어 들어가기C언어 들어가기
C언어 들어가기jaypi Ko
 
C언어 연산자에 대해 간과한 것
C언어 연산자에 대해 간과한 것C언어 연산자에 대해 간과한 것
C언어 연산자에 대해 간과한 것jaypi Ko
 
[확률통계]04모수추정
[확률통계]04모수추정[확률통계]04모수추정
[확률통계]04모수추정jaypi Ko
 
MFC 프로젝트 시작하기
MFC 프로젝트 시작하기MFC 프로젝트 시작하기
MFC 프로젝트 시작하기jaypi Ko
 
01 윈도우프로그램 들어가기
01 윈도우프로그램 들어가기01 윈도우프로그램 들어가기
01 윈도우프로그램 들어가기jaypi Ko
 
13 사용자 메세지 처리
13 사용자 메세지 처리13 사용자 메세지 처리
13 사용자 메세지 처리jaypi Ko
 
12 컨트롤에서의 메세지 처리
12 컨트롤에서의 메세지 처리12 컨트롤에서의 메세지 처리
12 컨트롤에서의 메세지 처리jaypi Ko
 
11 노티피케이션코드
11 노티피케이션코드11 노티피케이션코드
11 노티피케이션코드jaypi Ko
 
10 컨트롤윈도우
10 컨트롤윈도우10 컨트롤윈도우
10 컨트롤윈도우jaypi Ko
 
09 윈도우스타일
09 윈도우스타일09 윈도우스타일
09 윈도우스타일jaypi Ko
 
08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우jaypi Ko
 
07 윈도우 핸들
07 윈도우 핸들07 윈도우 핸들
07 윈도우 핸들jaypi Ko
 
06 일반적 유형의 프로그램
06 일반적 유형의 프로그램06 일반적 유형의 프로그램
06 일반적 유형의 프로그램jaypi Ko
 
05 윈도우 프로그램 유형
05 윈도우 프로그램 유형05 윈도우 프로그램 유형
05 윈도우 프로그램 유형jaypi Ko
 
04 이벤트처리
04 이벤트처리04 이벤트처리
04 이벤트처리jaypi Ko
 
03 첫번째프로그램
03 첫번째프로그램03 첫번째프로그램
03 첫번째프로그램jaypi Ko
 

Mehr von jaypi Ko (20)

CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Model
CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic ModelCVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Model
CVPR 2022 Tutorial에 대한 쉽고 상세한 Diffusion Probabilistic Model
 
개념 이해가 쉬운 Variational Autoencoder (VAE)
개념 이해가 쉬운 Variational Autoencoder (VAE)개념 이해가 쉬운 Variational Autoencoder (VAE)
개념 이해가 쉬운 Variational Autoencoder (VAE)
 
파이썬설치
파이썬설치파이썬설치
파이썬설치
 
객체지향 단어가 의미하는 것
객체지향 단어가 의미하는 것객체지향 단어가 의미하는 것
객체지향 단어가 의미하는 것
 
C언어 들어가기
C언어 들어가기C언어 들어가기
C언어 들어가기
 
C언어 연산자에 대해 간과한 것
C언어 연산자에 대해 간과한 것C언어 연산자에 대해 간과한 것
C언어 연산자에 대해 간과한 것
 
[확률통계]04모수추정
[확률통계]04모수추정[확률통계]04모수추정
[확률통계]04모수추정
 
MFC 프로젝트 시작하기
MFC 프로젝트 시작하기MFC 프로젝트 시작하기
MFC 프로젝트 시작하기
 
01 윈도우프로그램 들어가기
01 윈도우프로그램 들어가기01 윈도우프로그램 들어가기
01 윈도우프로그램 들어가기
 
13 사용자 메세지 처리
13 사용자 메세지 처리13 사용자 메세지 처리
13 사용자 메세지 처리
 
12 컨트롤에서의 메세지 처리
12 컨트롤에서의 메세지 처리12 컨트롤에서의 메세지 처리
12 컨트롤에서의 메세지 처리
 
11 노티피케이션코드
11 노티피케이션코드11 노티피케이션코드
11 노티피케이션코드
 
10 컨트롤윈도우
10 컨트롤윈도우10 컨트롤윈도우
10 컨트롤윈도우
 
09 윈도우스타일
09 윈도우스타일09 윈도우스타일
09 윈도우스타일
 
08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우
 
07 윈도우 핸들
07 윈도우 핸들07 윈도우 핸들
07 윈도우 핸들
 
06 일반적 유형의 프로그램
06 일반적 유형의 프로그램06 일반적 유형의 프로그램
06 일반적 유형의 프로그램
 
05 윈도우 프로그램 유형
05 윈도우 프로그램 유형05 윈도우 프로그램 유형
05 윈도우 프로그램 유형
 
04 이벤트처리
04 이벤트처리04 이벤트처리
04 이벤트처리
 
03 첫번째프로그램
03 첫번째프로그램03 첫번째프로그램
03 첫번째프로그램
 

Kürzlich hochgeladen

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 

Kürzlich hochgeladen (20)

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 

[신경망기초]오류역전파알고리즘구현

  • 1. 오류 역전파 알고리즘 구현 딥러닝을 위한 신경망 기초 nonezerok@gmail.com 프로그램 코드를 통해 오류역전파알고리즘에 대한 이해를 높일 수 있습니다. 여기서 제시되는 C 코드는 오류역전파알고리즘을 이해하는 데 목적을 두어 최대한 간결하게 작성되어 있습니다. 또한 Tensorflow 코드로 제공된 필기체 숫자인식을 통해 실제 사례에 어떻게 적용되는지를 살펴볼 수 있습니다. 신경망은 주어진 데이터에 따라 학습자가 조정해야 할 값들이 있습니다. 이 값들을 변경해 보면서 조정값들에 대한 경험치를 쌓는데 본 코드를 활용할 수 있습니다.
  • 2. 2 MLP for XOR pattern in C
  • 3. 3  = 1 1  = 1  = 0 1  = 0  = 0 0  = 0  = 1 0  = 0 Input Layer Hidden Layer Output Layer 1 1 Net0 Net1 Net2 0 1 2 w00 w10 w11 w21 w20 w02 0 w12 w22 x1 x2 y w01 Weight[3][3] out 포물선으로 구분
  • 4. 4 /* ========================================== * * Filename: bpnet.h * Author: James Matthews. * This is a tiny neural network that uses * back propagation for weight adjustment. * ========================================== */ #define BP_LEARNING(float)(0.5)// The learning coefficient. class CBPNet{ public: CBPNet(); ~CBPNet() {}; float Train(float, float, float); float Run(float, float); private: float m_fWeights[3][3];// Weights for the 3 neurons. float Sigmoid(float);// The sigmoid function. };
  • 5. 5 CBPNet::CBPNet() { srand((unsigned)(time(NULL))); for (inti=0;i<3;i++) { for (intj=0;j<3;j++) { m_fWeights[i][j] = (float)(rand())/(32767/2) -1; } } }
  • 6. 6 float CBPNet::Train(floati1, float i2, float y) { float net1, net2, i3, i4, out; net1 = 1*m_fWeights[0][0]+i1*m_fWeights[1][0]+i2*m_fWeights[2][0]; net2 = 1*m_fWeights[0][1]+i1*m_fWeights[1][1]+i2*m_fWeights[2][1]; i3 = Sigmoid(net1); i4 = Sigmoid(net2); net1 = 1*m_fWeights[0][2]+i3*m_fWeights[1][2]+i4*m_fWeights[2][2]; out = Sigmoid(net1);
  • 7. 7 float deltas[3]; deltas[2] = out*(1-out)*(y-out); deltas[1] = i4*(1-i4)*(m_fWeights[2][2])*(deltas[2]); deltas[0] = i3*(1-i3)*(m_fWeights[1][2])*(deltas[2]);  ←  1 −   −   ←  1 −   ,   Input Layer Hidden Layer Output Layer 1 1 Net0 Net1 Net2 0 1 2 w00 w10 w11 w21 w20 w02 0 w12 w22 x1 x2 y w01 Weight[3][3] out
  • 8. float v1 = i1, v2 = i2; for(int i=0;i<3;i++) { // Change the values for the output layer, if necessary. if (i == 2) { v1 = i3; v2 = i4; } m_fWeights[0][i] += BP_LEARNING*1*deltas[i]; m_fWeights[1][i] += BP_LEARNING*v1*deltas[i]; m_fWeights[2][i] += BP_LEARNING*v2*deltas[i]; } return out; } , ← , + ∆, ∆, =   =  when  is of the first layer
  • 9. 9 float CBPNet::Sigmoid(floatnum) { return (float)(1/(1+exp(-num))); } float CBPNet::Run(floati1, float i2) { float net1, net2, i3, i4; net1 = 1*m_fWeights[0][0]+i1*m_fWeights[1][0]+i2*m_fWeights[2][0]; net2 = 1*m_fWeights[0][1]+i1*m_fWeights[1][1]+i2*m_fWeights[2][1]; i3 = Sigmoid(net1); i4 = Sigmoid(net2); net1 = 1*m_fWeights[0][2]+i3*m_fWeights[1][2]+i4*m_fWeights[2][2]; return Sigmoid(net1); }
  • 10. 10 #define BPM_ITER2000 void main() { CBPNet bp; for (inti=0;i<BPM_ITER;i++) { bp.Train(0,0,0); bp.Train(0,1,1); bp.Train(1,0,1); bp.Train(1,1,0); } cout<< "0,0 = " << bp.Run(0,0) << endl; cout<< "0,1 = " << bp.Run(0,1) << endl; cout<< "1,0 = " << bp.Run(1,0) << endl; cout<< "1,1 = " << bp.Run(1,1) << endl; }
  • 12. 12 MLP on MNIST in Tensorflow
  • 13. 13 http://yann.lecun.com/exdb/mnist/ 28 28 28X28=768 • 5,5000개 학습 데이터 • 10,000개 테스트 데이터 MNIST
  • 15. 15 3 layers perceptron https://ml4a.github.io/demos/forward_pass_mnist/ 8번 뉴런 (노드)에서 가장 큰 값을 출력 8과 유사한 것 중 하나
  • 16. 16 ' ' https://github.com/rickiepark/tfk-notebooks ' import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) plt.imshow(mnist.train.images[100].reshape([28, 28]), cmap=plt.get_cmap('gray_r')) x = tf.placeholder("float32", [None, 784]) y = tf.placeholder("float32", shape=[None, 10]) W1 = tf.Variable(tf.truncated_normal([784, 100], stddev=0.1)) b1 = tf.Variable(tf.constant(0.1, shape=[100]))
  • 17. 17 t = tf.sigmoid(tf.matmul(x,W1) + b1) W2 = tf.Variable(tf.truncated_normal([100, 10], stddev=0.1)) b2 = tf.Variable(tf.constant(0.1, shape=[10])) z = tf.matmul(t,W2) + b2 y_hat = tf.nn.softmax(z) loss = tf.losses.softmax_cross_entropy(y, z) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_hat,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) sess = tf.Session() sess.run(tf.global_variables_initializer())
  • 18. 18 costs = [] for i in range(1000): x_data, y_data = mnist.train.next_batch(100) _, cost = sess.run([train, loss], feed_dict={x: x_data, y: y_data}) costs.append(cost) plt.plot(costs) for i in range(5): plt.imshow(mnist.test.images[i].reshape([28, 28]), cmap=plt.get_cmap('gray_r')) plt.show() print(sess.run(tf.argmax(y_hat,1), feed_dict={x: mnist.test.images[i].reshape([1,784])}))