본문 바로가기
데이터 청년 캠퍼스/연관분석, 인공신경망

[인공신경망] MNIST 데이터 실습

by 뚱뚜루뚱 2022. 7. 18.

1. 필요한 데이터 불러오기

# 데이터를 colab에 업로드
from google.colab import files
src = list(files.upload().values())[0]


from mnist import load_mnist

(x_train, t_train), (x_test, t_test) = load_mnist(flatten = True, normalize = False)
print (x_train.shape)
print (t_train.shape)
print (x_test.shape)
print (t_test.shape)

 

2. 첫 번째 훈련데이터를 이미지로 확인

# 첫 번째 훈련데이터를 이미지로 확인
import numpy as np
import matplotlib.pyplot as plt

label = t_train[0]
print(label)

img = x_train[0]
print(img.shape)  

img = img.reshape(28,28) 
print(img.shape)  
plt.imshow(img)

 

3. 가중치 파일을 이용해 추론 수행

# 가중치 파일을 colab으로 불러오기
from google.colab import files
src = list(files.upload().values())[0]

import pickle # 가중치 읽어들일 라이브러리


# MNIST 데이터를 읽어오는 함수
def get_data():
  (x_train, t_train), (x_test, t_test) = load_mnist(flatten = True, normalize = True, one_hot_label=False)
  return x_test, t_test
  
  
# 가중치 파일을 읽어오는 함수
def init_network():
    with open ('sample_weight.pkl', 'rb') as f :
        network = pickle.load(f)
    return network
    
    
# 입력 데이터와 가중치의 형태
x, t = get_data()
network = init_network()
W1, W2, W3 = network['W1'], network['W2'], network['W3']

print ('x:',x.shape)
print ('x[0]:',x[0].shape) 
print ('W1:',W1.shape)
print ('W2:',W2.shape)
print ('W3:',W3.shape)

    
# 예측 모델
def predict(network, x):
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']
    
    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, W3) + b3
    z3 = softmax(a3)
    y = z3
    
    return y

 

4. 활성화 함수

def sigmoid(x):
    return 1 / (1+np.exp(-x))

def softmax(a):
    c = np.max(a)
    exp_a= np.exp(a-c)
    sum_exp_a = np.sum(exp_a)
    y = exp_a / sum_exp_a
    return y

 

5. 모델 평가

x, t = get_data()
network = init_network()

accuracy_cnt = 0

for i in range (len(x)) :
    y = predict(network, x[i])
    p = np.argmax(y)
    if p == t[i] :
        accuracy_cnt +=1

print (f'Accuracy: { accuracy_cnt/len(x) }')

 

6. 입력데이터와 가중치의 형태

batch_size = 100  
accuracy_cnt = 0

# 100개씩 묶어서 예측 처리
for i in range(0,len(x), batch_size) :

    x_batch = x[i:i+ batch_size ]
    y_batch = predict(network, x_batch )
   
    p = np.argmax(y_batch, axis = 1)
    accuracy_cnt += np.sum(p==t[i:i+batch_size])

print (f'Accuracy: { accuracy_cnt/len(x) }')