[내 뉴럴 네트워크 만들기/2부] 2. 파이썬으로 작성하는 신경망
1. 개요
2. 파이썬 신경망 기본틀
2-1. 크래스 초기화 함수, __init__()
2-2. 초기 가중치
2-3. 조회 함수 , query()
2-4. 훈련 함수, train()
3. 소규모 신경망
----------------------------------------------------------------------------------------------
[참고서] Make Your Own Neural Networks, Tariq Rashid [book][검색링크]
----------------------------------------------------------------------------------------------
1. 개요
최소한의 파이썬으로 간단한 신경망을 작성해보자.
2. 파이썬 신경망 기본틀
신경망의 파이썬 크래스 기본 골격은 다음과 같은 소속함수를 두기로 한다.
- 초기화 함수(크래스 구성자): 신경망을 구성하는 입력층, 은익층 그리고 출력층의 노드 갯수를 정한다.
- 학습 함수: 각층의 노드들 사이의 연결강도(가중치)를 갱신한다. 갱신될 가중치는 학습 자료에 따라 목표 치와 비교하여 갱신될 가중치가 계산된다.
- 조회 함수: 신경망을 구성하는 각 층의 노드에 입력이 주어진 후 계산된 출력을 조회한다.
신경망 크래스 골격은 다음과 같다. 함수의 내용은 아직 비었다.
# Neural network class definition
class neuralNetwork:
# Initialise the neural network
def __init__():
pass
# Train the neural networks
def train():
pass
# query the neural network
def query():
pass
2-1. 크래스 초기화 함수, __init__()
신경망을 구성하는 각 층의 노드 수를 설정하기 위해 크래스 neuralNetwork의 초기화 함수를 아래와 같이 변경한다.
# Initialise the neural network
def __init__(self, inputnodes, hiddennodes,
outputnodes, learningrate):
self.inodes = inputnodes # number of input nodes
self.hnodes = hiddennodes
self.onodes = outputnodes
self.lr = learningrate
pass
각층의 노드 갯수를 주고 크래스를 사례화 하여 신경망을 구성한다.
>>> input_nodes = 3
>>> hidden_nodes = 3
>>> output_nodes = 3
>>> learning_rate = 0.3
>>> n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
2-2. 초기 가중치
각층의 노드들 사이의 연결강도는 신경망의 핵심이다. 학습은 이 연결강도의 조정과정이다. 연결강도는 행렬로 표현한다. 연결의 시작을 행으로, 종착을 열로 나타낸다. 예를들어,
- wih은 입력층에서 은닉층으로 연결되는 가중치 행렬이다. wih[1][3] 은 입력층 1번째 노드에서 은닉층 3번째 노드의 연결 강도다.
- who 는 은닉층에서 출력층으로 연결되는 가중치 행렬이다. who[3][2] 는 은닉층 3번째 노드에서 출력층 2번째 노드의 연결 강도다.
초기 가중치는 numpy 모듈의 난수 발생 함수를 사용하여 줄 수 있다. 난수 발생 함수는 다음과 같다.
>>> import numpy
>>> numpy.random.rand()
0.6175598212712633
난수를 갖는 3행 3렬의 행렬을 단 한문장으로 쉽게 만들 수 있다. 과학 함수 모듈 SciPy의 난수 발생 함수는 [링크]를 참조한다.
>>> wih = numpy.random.rand(3, 3)
>>> print(wih)
[[0.69180601 0.49551435 0.60070353]
[0.78342214 0.53015784 0.73122591]
[0.04353726 0.62959035 0.7916583 ]]
numpy의 난수는 0.0 과 1.0 사이의 값을 갖는다. 범위를 -0.5와 +0.5 사이 값으로 변경해 주어야 한다. 한 문장으로 모든 행렬 값을 쉽게 병경 할 수 있다. 파이썬의 코드 작성에 효율적인 면을 보여준다.
>>> wih = numpy.random.rand(3, 3) - 0.5
>>> print(wih)
[[ 0.30124198 -0.23037785 0.18063384]
[-0.24784492 0.35512545 -0.44099057]
[ 0.44976501 -0.40828219 0.44500375]]
초기 가중치를 무작위 난수보다 정규 확률 분포를 따르는 난수가 효과적이다. 정규 확률 분포 난수 발생 함수 numpy.random.normal()는 [링크]를 참조한다. 이 함수를 이용하여 0.0 을 중심으로 대칭인 정규 확율(가우시안) 분포에서 난수를 생성한다. 한개의 난수값 뿐만 아니라 행렬을 쉽게 만들 수 있다. 출력층의 노드 갯수의 역수, pow(onodes, -0.5)를 확률분포의 표준 편차로 취하여 발생한 난수 행렬을 만드는 예는 다음과 같다.
>>> # normal probability distribution rando generator
>>> import numpy
>>> inodes = 3
>>> hnodes = 4
>>> wih = numpy.random.normal(0.0, pow(hnodes, -0.5), (hnodes, inodes))
>>> print(wih)
[[ 0.42839628 -0.06340692 0.56184273]
[ 0.68782127 0.26616802 -0.35102333]
[ 0.94193363 -0.23215167 -0.04476711]
[ 0.07428921 0.2611703 0.62385664]]
>>> onodes = 5
>>> who = numpy.random.normal(0.0, pow(onodes, -0.5), (onodes, hnodes))
>>> print(who)
[[-0.67086208 -0.52284949 -0.42519078 -0.18905072]
[-0.06233622 0.28244396 0.48764996 0.37380161]
[-0.39578609 0.38793941 0.13654488 -0.29288628]
[ 0.0166917 -0.25951234 0.42738579 0.54957168]
[ 0.04814966 -0.47340498 0.42078217 -0.40487517]]
신경망의 연결강도를 임의의 난수 대신 정규 확률 분포를 가지는 난수로 초기화 해준다.
self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5),
(self.hnodes, self.inodes))
self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5),
(self.onodes, self.hnodes))
2-3. 조회 함수, query()
조회 함수 query()는 노드들의 출력 계산을 수행한다. 신경망을 구성하는 각층의 노드들 사이에 가중치를 곱한 누적 값을 발화 함수 (시그모이드 함수)를 통하여 출력을 계산한다. 연결 강도곱의 누적은 행렬과 벡터의 내적(inner product)이다. 입력 벡터 I 에 대하여 연결 강도 행렬 W의 내적은 다음과 같다.
X_hidden = W_input_hidden . transpose(I_input)
입력층의 노드 갯수가 3, 은닉층의 노드 갯수는 4일 경우,
|X[0]| = |W[0][0] W[1][0] W[2][0]| . |I[0]|
|X[1]| |W[0][1] W[1][1] W[2][1]| |I[1]|
|X[2]| |W[0][2] W[1][2] W[2][2]| |I[3]|
|X[3]| |W[0][3] W[1][3] W[2][3]|
파이썬의 numpy 모듈은 행렬과 벡터의 내적을 처리하는 함수를 가지고 있다.
X_hidden = numpy.dot(self.wih, I)
높은 추상화 수준의 언어(객체 선언과 할용이 매우 유연하다)인 파이썬은 라이브러리 구축과 활용에 매우 유리하다. 많은 사용자들에 의해 방대한 라이브러리(모듈)들을 손쉽게 공유할 수 있다. 비교적 현대적인 언어로서 과학기술 계산, 자료처리(인공지능), 데이터 시각화 등 다양한 라이브러리들이 있다. 은닉층 노드의 최종 값은 발화함수의 출력이다.
|X[0]| = |sigmoid(X[0])|
|X[1]| |sigmoid(X[1])|
|X[2]| |sigmoid(X[2])|
|X[3]| |sigmoid(X[3])|
시그모이드 함수를 거친 은닉층의 출력은 다음과 같다.
O_hidden = sigmoid(X_hidden)
파이썬 SciPy 라이브러리에 시그모이드 함수는 expit() 다. 이 함수를 사용하기 위해 라이브러리를 불러온다.
# scipy.special for the sigmoid function expit()
import scipy.special
노드의 출력을 결정하는 활성 함수는 시그모이드 외에 다양하게 구현된다. 굳이 복잡한 지수함수를 가진 시그모이드 보다 좀더 단순화된 함수를 사용한다. 계산과 구현의 단순화를 위해 연속함수 대신 불연속 함수가 사용되기도 한다. 대규모 계산을 요구하는 신경망을 감안하면 연산기 단순화(값의 양자화)가 실용적인 면에서 중요한 과제다. 응용에 따라 효율적인 발화함수의 구현은 나중으로 미루고 시그모이드 함수의 원형[참고]을 발화 함수로 사용하기로 한다.
# activation function is the sigmoid function
self.activation_function = lambda x: scipy.special.expit(x)
'익명 함수(anoymous)'라고 부르는 '람다(lambda)' 수식(expression)으로 '함수'를 기술하는 기법이다. 한 문장으로 함수를 간결하게 기술할 수 있다.
lambda 인자: 표현식
람다 식으로 기술한 활성함수를 사용하는 방법은 일반 함수와 같다.
#calculate the signal emerging from hidden layer
hidden_output = self.activation_function(O_hidden)
신경망을 구성하는 두 층 사이의 노드 연결과 출력은 다음과 같다. 입력 벡터와 연결 강도(가중치) 행렬의 내적과 활성함수 적용후 출력이다.
# calculate signals into hidden layer
hidden_inputs = numpy.dot(self.wih, inputs)
# calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs)
동일한 방식으로 은닉층과 출력층을 연결하여 신경망 최종 출력을 얻는다.
# calculate signals into final output layer
final_inputs = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
초기화와 조회 함수가 포함된 파이썬 코드는 다음과 같다. 학습 함수 train() 은 아직 작성 전이다.
# Filename: Code_init_query.py
# neural network class definition
class neuralNetwork :
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes,
learningrate) :
# set number of nodes in each input, hidden, output layer
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
# link weight matrices, wih and who
# weights inside the arrays are w_i_j,
# where link is from node i to node j in the next layer
self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5),
(self.hnodes, self.inodes))
self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5),
(self.onodes, self.hnodes))
# learning rate
self.lr = learningrate
# activation function is the sigmoid function
self.activation_function = lambda x: scipy.special.expit(x)
pass
# train the neural network
def train() :
pass
# query the neural network
def query(self, inputs_list) :
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
print(inputs)
# calculate signals into hidden layer
hidden_inputs = numpy.dot(self.wih, inputs)
# calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer
final_inputs = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output
final_outputs = self.activation_function(final_inputs)
return final_outputs
pass # End of class, neuralNetwork
실행,
$ python3
Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
행렬 곱과 시그모이드 함수를 사용하기 위해 모두 들어오기,
>>> import numpy
>>> import scipy.special
파이썬 파일을 읽어 실행,
>>> exec(open('Code_init_query.py').read())
신경망 크래스 사례화하여 소규모 신경망 만들기,
>>> input_nodes = 5
>>> hidden_nodes = 4
>>> output_nodes = 3
>>> learning_rate = 0.3
>>> n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
입력층과 은닉층 사이의 연결 가중치 행렬 확인,
>>> print(n.wih)
[[-0.78217197 0.5808482 -0.31876802 1.64631682 -0.28874034]
[ 0.17742955 -0.26017423 -0.55911973 -0.40947595 0.41022274]
[-0.28092837 -0.04689308 -0.25862563 -0.67334743 -0.85635187]
[-0.44649879 0.31916959 0.05223414 -0.06373131 -0.46721884]]
은닉층과 출력층 사이의 연결 가중치 행렬 확인,
>>> print(n.who)
[[ 0.64205114 0.50799958 1.45701532 -1.02826693]
[ 0.56086822 0.46135494 -0.55627495 0.40996956]
[-0.63063029 -0.71400507 0.82037014 1.43052149]]
신경망 (순방향) 실행해 보자. 입력이 1행짜리 리스트 형식이므로 행렬 내적을 수행 하려면 전치(transpose)행렬로 바꿔 주어야 한다.
>>> o = n.query([1.0, 0.5, -1.5, 1.5, 2.0])
[[ 1. ]
[ 0.5]
[-1.5]
[ 1.5]
[ 2. ]]
>>> print(o)
[[0.69641302]
[0.7060551 ]
[0.32236108]]
아직 의미있는 훈련을 하지 않았지만 신경망의 순방향 작동을 확인 해봤다. 파이썬을 사용하면 최소한의 코드로 알고리즘을 기술 할 수 있다.
2-4. 훈련 함수, train()
이제 신경망을 훈련시켜보자. 훈련은 먼저 query()로 순방향 계산을 수행하고 이를 토대로 목표와 차분을 역전파하여 가중치를 갱신한다. 학습 함수 train()은 두개의 인자(시험입력과 목표)를 갖는다. 순방향 입력에 대하여 순방향 계산을 수행 한 후,
# train the neural network
def train(self, inputs_list, targets_list):
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
targets = numpy.array(targets_list, ndmin=2).T
# calculate signals into hidden layer
hidden_inputs = numpy.dot(self.wih, inputs)
# calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer
final_inputs = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
pass
출력과 목표의 차를 구한다.
# error is the (target - actual)
output_errors = target - final_output
출력층의 오차는 직전의 은닉층과 결합 가중치 갱신을 위해 역전파된다. 은닉층 오차 계산은 다음과 같다.
errors_hidden = transpose(Weight_hidden_output) . errors_output
1부에서 다뤘던 가중치 갱신량은 다음과 같다. 두 층 사이의 각 노드들이 연결되는 가중치의 갱신량이다.

위의 식에서 은닉층 노드는 색인 j로 출력층 노드는 색인 k라면,
self.lr -> (alpha)
Ek -> output_errors
sigmoid(Ok) -> final_outputs
Oj -> hidden_outputs
은닉층과 출력층의 연결 가중치 갱신을 파이썬 코드로 옮기면 다음과 같다.
# update the weights for the links between the hidden and output layers
self.who += self.lr *
numpy.dot(
(output_errors*final_outputs*(1.0-final_outputs)),
numpy.transpose(hidden_outputs))
연속적으로 입력층과 은닉층 사이의 연결 강도까지 확장하면 다음과 같다.
self.wih += self.lr *
numpy.dot(
(hidden_errors*hidden_outputs*(1.0-hidden_outputs)),
numpy.transpose(inputs))
학습 함수까지 작성된 신경망 파이썬 코드는 아래 링크에서 받을 수 있다.
https://github.com/makeyourownneuralnetwork/makeyourownneuralnetwork/blob/master/part2_neural_network.ipynb
3. 소규모 신경망
소규모 신경망의 내용은 다음과 같다.
# python notebook for Make Your Own Neural Network
# (c) Tariq Rashid, 2016
# license is GPLv2
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# neural network class definition
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes,
learningrate):
# set number of nodes in each input, hidden, output layer
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
# link weight matrices, wih and who
# weights inside the arrays are w_i_j,
# where link is from node i to node j in the next layer
# w11 w21
# w12 w22 etc
self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5),
(self.hnodes, self.inodes))
self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5),
(self.onodes, self.hnodes))
# learning rate
self.lr = learningrate
# activation function is the sigmoid function
self.activation_function = lambda x: scipy.special.expit(x)
pass
# train the neural network
def train(self, inputs_list, targets_list):
# convert inputs list to 2d array for transpose operation
inputs = numpy.array(inputs_list, ndmin=2).T
targets = numpy.array(targets_list, ndmin=2).T
# calculate signals into hidden layer
hidden_inputs = numpy.dot(self.wih, inputs)
# calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer
final_inputs = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
# output layer error is the (target - actual)
output_errors = targets - final_outputs
# hidden layer error is the output_errors,
# split by weights, recombined at hidden nodes(Transpose!)
hidden_errors = numpy.dot(self.who.T, output_errors)
# update the weights for the links
# between the hidden and output layers
self.who += self.lr *
numpy.dot(
(output_errors * final_outputs *
(1.0 - final_outputs)),
numpy.transpose(hidden_outputs))
# update the weights for the links
# between the input and hidden layers
self.wih += self.lr *
numpy.dot(
(hidden_errors * hidden_outputs *
(1.0-hidden_outputs)),
numpy.transpose(inputs))
pass
# query the neural network
def query(self, inputs_list):
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
# calculate signals into hidden layer
hidden_inputs = numpy.dot(self.wih, inputs)
# calculate the signals emerging from hidden layer
hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer
final_inputs = numpy.dot(self.who, hidden_outputs)
# calculate the signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
return final_outputs
간단한 신경망 이지만 여러 실험을 해볼 수 있다. 아래의 테스트벤치 코드를 가지고 실험해보자.
if __name__=="__main__":
# number of input, hidden and output nodes
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
# learning rate is 0.3
learning_rate = 0.3
# create instance of neural network
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes,
learning_rate)
input_list = [0.0, 1.0, 0.0]
target_list = [0.0, 0.0, 1.0]
for k in range(100):
n.train(input_list, target_list)
pass
print('Trained with test', input_list, ', target', target_list)
# test query
rand = lambda : abs(numpy.random.rand())
print('Query Test:')
for k in range(10):
query_list = [rand()/2.0, 1.0, rand()/2.0]
output_list = numpy.transpose(n.query(query_list))
print(f"{query_list}", '->', output_list, end="")
if (output_list[0,2] < 0.9):
print('<----------Oops!')
else :
print()
pass
----
입력을 [0 1 0] , 목표를 [0 0 1]로 주고 100회 반복 학습을 시킨 후 시험 입력을 넣어 보면 결과가 별로 신통치 않다.
-----
$ python3 part2_neural_network.py
Trained with test [0.0, 1.0, 0.0] , target [0.0, 0.0, 1.0]
Query Test:
[0.15031, 1.0, 0.12314] -> [[0.16026 0.15989 0.87123]]<----------Oops!
[0.04647, 1.0, 0.42817] -> [[0.15789 0.15930 0.87107]]<----------Oops!
[0.07979, 1.0, 0.49753] -> [[0.15724 0.15932 0.87088]]<----------Oops!
[0.26465, 1.0, 0.07751] -> [[0.16033 0.16023 0.87109]]<----------Oops!
[0.43167, 1.0, 0.45617] -> [[0.15662 0.16007 0.87016]]<----------Oops!
[0.36737, 1.0, 0.19353] -> [[0.15895 0.16027 0.87081]]<----------Oops!
[0.00176, 1.0, 0.07209] -> [[0.16126 0.15959 0.87140]]<----------Oops!
[0.10080, 1.0, 0.01487] -> [[0.10591 0.12179 0.92038]]
[0.01896, 1.0, 0.26416] -> [[0.10763 0.12263 0.91782]]
[0.03633, 1.0, 0.37903] -> [[0.10798 0.12269 0.91724]]
----------------------
소규모 신경망으로 할 수 있는 것은 별로 없다는 것을 알 수 있다. 파이썬으로 작성한 코드가 작동 한다는 점만 확인하는데 만족하자. 대규모 네트워크를 구성하여 방대한 자료를 기반으로 학습해야 한다. 최소한의 파이썬을 익혔다. 다음에는 본격적으로 손글씨 이미지를 받아 훈련시키고 인식하는 신경망을 작성해 보기로 하자.