본문 바로가기

컴퓨터/인공지능 및 기계학습 개론1

밑바닥부터 시작하는 딥러닝 3.6.2 신경망의 추론 처리(os.pardir이 안될 때)

3.6.2에서 MNIST 데이터셋을 가지고 추론을 수행하는 신경만을 구현하였다.

이 때, ch03 안에 있는 Python 프로그램이 부모디렉토리에 있는 Python 프로그램을 불러오기 위하여 다음과 같은 과정을 진행하였다.


github.com/oreilly-japan/deep-learning-from-scratch

 

oreilly-japan/deep-learning-from-scratch

『ゼロから作る Deep Learning』(O'Reilly Japan, 2016). Contribute to oreilly-japan/deep-learning-from-scratch development by creating an account on GitHub.

github.com

주어진 링크를 통해 포크 및 클론한 파일에서 사용하면 된다.


import sys, os
sys.path.append(os.pardir)
import numpy as np
import pickle
from dataset.mnist import load_mnist

하지만 내 경우 이를 실행하면 다음과 같은 에러가 발생하였다.

 

찾아본 결과, 주어진 문제는 2행에서 os.pardir으로 부모 디렉토리를 지정해줌으로써 부모 디렉터리의 파일을 가져올 수 있도록 설정하는 과정을 필요로 한다. 하지만 일련의 에러로 인하여 이를 제대로 하지 못하는 상황으로 보였다.

 

따라서 다른 과정을 통하여 부모 디렉토리를 지정하는 방법을 찾아야 했다.

 

www.geeksforgeeks.org/python-os-pardir-method-with-example/

 

Python - os.pardir() method with example - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

다음 링크에서 해답을 제시해주었다.

 

# Python program to demonstrate 
# os.pardir 


import os 


# current working directory 
path = os.getcwd() 
print("Current Directory:", path) 

# parent directory 
parent = os.path.join(path, os.pardir) 

# prints parent directory 
print("\nParent Directory:", os.path.abspath(parent)) 

이를 이용하여 부모 디렉토리를 설정하고 프로그램을 실행하였다.

 

import sys, os
path = os.getcwd()
parent = os.path.join(path, os.pardir)
sys.path.append(os.path.abspath(parent))

from dataset.mnist import load_mnist
from PIL import Image
import numpy as np
import pickle

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

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

def get_data():
    (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=True)
    return x_test, t_test

def init_network():
    with open("sample_weight.pkl", "rb") as f:
        network = pickle.load(f)
    
    return network

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
    y = softmax(a3)

    return y

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

batch_size = 100
accuracy_cnt = 0

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(str(float(accuracy_cnt)/len(x)))

   

 


또는 sample_weight.pkl이 분명 폴더 내에 있는데 계속 없다고 하는 경우이다.

anaconda로 가상환경을 만들었을 때, 디렉토리 설정이 잘못 되어 있었다.

나는 deep안에 ch03, dataset 폴더가 있다. 그런데 보면 현재 디렉토리가 ch03이 아닌 ch03의 부모디렉토리로 설정되어 있다. 따라서 deep 폴더 내에 sample_weight.pkl이 없으므로 에러가 발생되는 것이였다.

 

이를 해결하기 위하여 터미널에서 직접 "cd ch03"을 하여 ch03로 이동 후, "python (파일이름).py"을 실행하였더니 정상적으로 출력되었다.