본문으로 바로가기

파일의 IT 블로그

  1. Home
  2. 프로그래밍/Python
  3. [Python] Mnist 데이터를 이용한 인공신경망 손글씨 인식

[Python] Mnist 데이터를 이용한 인공신경망 손글씨 인식

· 댓글개 · KRFile
import numpy as np #행렬사용
import matplotlib.pyplot
import scipy.special
%matplotlib inline

#AI Class
class neuralNetWork:
    
    #신경망 초기화
    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        # 입력, 은닉, 출력 게층의 노드 개수 설정
        self.inodes = input_nodes
        self.hnodes = hidden_nodes
        self.onodes = output_nodes
        
        #학습률
        self.lr = learning_rate
        
        #가중치 행렬 생성 (랜덤값 -0.5 ~ +0.5)
        self.wih = (np.random.rand(self.hnodes, self.inodes) - 0.5) #input -> hidden
        self.who = (np.random.rand(self.onodes, self.hnodes) - 0.5) #hidden -> output
        pass
    
        #활성화 함수
        self.activation_function = lambda x: scipy.special.expit(x)
     
    #신경망 학습
    def train(self, inputs_list, targets_list):
        #입력 리스트를 2차원 행렬로 변환
        inputs = np.array(inputs_list, ndmin=2).T   #전치행렬 - 대각선 변환
        targets = np.array(targets_list, ndmin=2).T #정답행렬 - 대각선 변환
        
        #---------- 순전파 -------------#
        # -- input -> hidden
        # 은닉 계층으로 들어오는 신호를 계산
        hidden_inputs = np.dot(self.wih, inputs)
        
        # 은닉 계층에서 나가는 신호를 sigmoid 화
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # -- hidden -> output
        # 출력 계층으로 들어오는 신호를 계산
        final_inputs = np.dot(self.who, hidden_outputs)
        
        # 출력 계층에서 나가는 신호를 계산
        final_outputs = self.activation_function(final_inputs)
        
         #-------------역전파-------------#
  
        # 오차값 검증 (실제값 - 계산값)
        output_errors = targets - final_outputs
        
        # 은닉계층 오차 (가중치에 의해 나뉜 출력 계층의 오차들을 재조합해 계산)
        hidden_errors = np.dot(self.who.T, output_errors)
        
        # 은닉 계층과 출력 계층간의 가중치 업데이트
        self.who += self.lr * np.dot(output_errors * final_outputs * (1.0 - final_outputs),
                                        np.transpose(hidden_outputs))
        
        # 입력 계층과 은닉 계층 간의 가중치 업데이트
        self.wih += self.lr * np.dot(hidden_errors * hidden_outputs * (1.0 - hidden_outputs),
                                        np.transpose(inputs))
        
        pass
    
    #신경망에 질문하기
    def query(self, inputs_list):
        #입력 리스트를 2차원 행렬로 변환
        inputs = np.array(inputs_list, ndmin=2).T #전치행렬 - 대각선 변환
        
        #---------- 순전파 -------------#
        # -- input -> hidden
        # 은닉 계층으로 들어오는 신호를 계산
        hidden_inputs = np.dot(self.wih, inputs)
        
        # 은닉 계층에서 나가는 신호를 sigmoid 화
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # -- hidden -> output
        # 출력 계층으로 들어오는 신호를 계산
        final_inputs = np.dot(self.who, hidden_outputs)
        
        # 출력 계층에서 나가는 신호를 계산
        final_outputs = self.activation_function(final_inputs)
        
         #-------------------------------#
            
        
        
        return final_outputs
        
input_nodes = 784
hidden_nodes = 100
output_nodes = 10
#학습률 설정
lr = 0.3

n = neuralNetWork(input_nodes,hidden_nodes, output_nodes, lr)

data_file = open('mnist_train.csv', 'r')
data_list = data_file.readlines()
data_file.close()

for record in data_list:
    #레코드를 심표에 의해 분리
    all_values = record.split(',')
    #입력 값의 범위와 값 조정
    inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
    targets = np.zeros(output_nodes) + 0.01
    targets[int(all_values[0])] = 0.99
    n.train(inputs, targets)
    pass
    
scorecard = []

for record in test_data_list:
    all_values = record.split(',')
    correct_label = int(all_values[0])
    print(correct_label, 'correct label')
    inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
    outputs = n.query(inputs)
    label = np.argmax(outputs)
    print(label, 'network\'s answer')
    
    if (label == correct_label):
        scorecard.append(1)
    else:
        scorecard.append(0)
print(scorecard)

scorecard_array = np.asfarray(scorecard)
print('performance =', scorecard_array.sum() / scorecard_array.size * 100, '%')

SNS 공유하기
💬 댓글 개
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

이모티콘을 클릭하면 댓글창에 입력됩니다.