데이터 과학

MNIST 예제 본문

인공지능/딥러닝 -파이썬 인공지능

MNIST 예제

티에스윤 2022. 9. 14. 09:17

이번에는 MNIST 예제를 찾아서 공부해 봅시다. 

 

구글에 MNIST 예제로 검색을 하면 많은 예제들이 나옵니다.

텐서플로우를 이용하는 예제도 있고, 파이썬 라이브러리를 활용한 예제도 있습니다. 

 

온라인에서도 예제를 만날 수 있습니다. 

아래 온라인 예제 사이트는 양방향 LSTM 알고리즘까지 구현해 낸 사이트입니다. 

Basic Convnet에 들어가서 마우스로 숫자를 그리면 알맞은 숫자가 화면에 나타납니다. 

 

https://transcranial.github.io/keras-js/#/

 

Keras.js - Run Keras models in the browser

 

transcranial.github.io

 

숫자 6을 입력했을때 나타나는 결과와 적용되는 다양한 함수들

 

 

그리고, 텐서플로우 놀이터(playground)라는 공간도 있습니다. 

히든 레이어와 노드의 개수를 지정하고 판별 함수 설정을 시각화하여서 인공지능 학습을 도와주는 사이트입니다. 

딥러닝을 공부 할 때 머릿속에 개념 잡기 어려울 때 이런 시각화 프로그램이 많은 도움이 될 것입니다. 

 

http://playground.tensorflow.org/

 

Tensorflow — Neural Network Playground

Tinker with a real neural network right here in your browser.

playground.tensorflow.org

 

 

AI Platform용 AI Explanations 소개라는 사이트가 있는데 이미지 프로세싱에 대한 내용이 자세하게 담겨 있습니다. 한국어로 직역이 되어 있어서 읽기가 조금 어렵지만 용어들을 정리해서 읽어보면 이미지 학습에 대한 내용을 이해 할 수 있습니다.

 

 

https://cloud.google.com/ai-platform/prediction/docs/ai-explanations/overview?hl=ko 

 

AI Platform용 AI Explanations 소개  |  AI Platform Prediction  |  Google Cloud

의견 보내기 AI Platform용 AI Explanations 소개 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 이 제품은 차세대 AI Platform인 Vertex AI에서 사용 가능합니다. 리소스

cloud.google.com

 

이 정도만 읽고 실습해봐도 많은 시간이 흘러갈 것입니다. 

 

MNIST 소스를 깃허브에 소개한 사이트도 있습니다. 

MNIST 데이터셋이 있는 사이트입니다. 

 

https://github.com/freebz/Make-Your-Own-Neural-Network/tree/master/mnist_dataset

 

GitHub - freebz/Make-Your-Own-Neural-Network: 신경망 첫걸음

신경망 첫걸음. Contribute to freebz/Make-Your-Own-Neural-Network development by creating an account on GitHub.

github.com

 

 

MNIST 관련 책인 신경망 첫걸음에서 소개한 프로그램 소스가 있는 사이트입니다. 

 

https://github.com/kimjooeun/neuralnetwork_firstwalk

https://github.com/bbongcol/first-steps-of-neural-network

 

GitHub - bbongcol/first-steps-of-neural-network: 책 "신경망 첫걸음"의 Python Code

책 "신경망 첫걸음"의 Python Code. Contribute to bbongcol/first-steps-of-neural-network development by creating an account on GitHub.

github.com

 

MNIST 예제들을 보면 대부분 텐서플로우를 기반으로 코딩이 되어 있는데, 텐서플로우 없이도 운영할 수 있습니다. 

그 예제를 보면서 조금씩 이해해 봐도 됩니다. 

 

 

전체 소스 코드 

 

https://github.com/makeyourownneuralnetwork/makeyourownneuralnetwork/blob/master/part2_neural_network_mnist_data.ipynb

 

makeyourownneuralnetwork/part2_neural_network_mnist_data.ipynb at master · makeyourownneuralnetwork/makeyourownneuralnetwork

Code for the Make Your Own Neural Network book. Contribute to makeyourownneuralnetwork/makeyourownneuralnetwork development by creating an account on GitHub.

github.com

 

이에 대한 설명

 

import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# library for plotting arrays
import matplotlib.pyplot
# ensure the plots are inside this notebook, not an external window
%matplotlib inline


# 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
        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
        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
# number of input, hidden and output nodes
# 입력, 은닉, 출력 계층의 노드 개수 설정

input_nodes = 784
hidden_nodes = 200
output_nodes = 10

# 학습률
learning_rate = 0.1

# 인공 신경망 생성
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)

# load the mnist training data CSV file into a list
training_data_file = open("./drive/MyDrive/minist_dataset/mnist_train_100.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()


# train the neural network
# epochs is the number of times the training data set is used for training




epochs = 5


for e in range(epochs):
    # go through all records in the training data set
    for record in training_data_list:
        # split the record by the ',' commas
        all_values = record.split(',')
        # scale and shift the inputs
        inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
        # create the target output values (all 0.01, except the desired label which is 0.99)
        targets = numpy.zeros(output_nodes) + 0.01
        # all_values[0] is the target label for this record
        targets[int(all_values[0])] = 0.99
        n.train(inputs, targets)
        pass
    pass

#이젠 테스트 데이타를 로딩한다.
# load the mnist test data CSV file into a list
test_data_file = open("./drive/MyDrive/minist_dataset/mnist_test_10.csv", 'r')
test_data_list = test_data_file.readlines()
test_data_file.close()


scorecard = []

# go through all the records in the test data set
for record in test_data_list:
    # split the record by the ',' commas
    all_values = record.split(',')
    # correct answer is first value
    correct_label = int(all_values[0])
    # scale and shift the inputs
    inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
    # query the network
    outputs = n.query(inputs)
    # the index of the highest value corresponds to the label
    label = numpy.argmax(outputs)
    # append correct or incorrect to list
    if (label == correct_label):
        # network's answer matches correct answer, add 1 to scorecard
        scorecard.append(1)
    else:
        # network's answer doesn't match correct answer, add 0 to scorecard
        scorecard.append(0)
        pass

    pass

# calculate the performance score, the fraction of correct answers
scorecard_array = numpy.asarray(scorecard)
print ("performance = ", scorecard_array.sum() / scorecard_array.size)



#테스트 데이타 첫번째 값을 보면 7 이다는 것을 알 수 있다.

all_values = test_data_list[0].split(',')
print(all_values[0])
image_array = numpy.asfarray(all_values[1:]).reshape((28,28))
matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')

 

 

 

 

 

https://blog.naver.com/PostView.nhn?isHttpsRedirect=true&blogId=beodeulpiri&logNo=221025358671&parentCategoryNo=&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView

 

[Python] MNIST 손글씨 인식 인공지능 맛보기

MNIST 라는 손글씨 이미지 데이타 셋이 있는데 이걸로 딥러닝 알고리즘의 성능을 테스트 하는데 많이 ...

blog.naver.com

 

 

 

 

그리고, 텐서플로우 홈페이지에서는 MNIST를 패션 MNIST로 데이터 소스를 바꿔서 소개하고 있습니다. 

딥러닝의 기초가 MNIST이다 보니 다양한 방법으로 MNIST에 대한 프로그래밍을 하고 있습니다. 

인터넷에  관련된 자료도 많이 있고, 관심만 있으면 MNIST 프로그래밍을 쉽게 할 수 있습니다. 

 

 

패션 MNIST는 아래 예제를 통해 공부해 봅시다. 

 

https://tsyoon.tistory.com/36

 

Fashion MNIST

딥러닝을 공부할 때 가장 먼저 만나게 되는 예제가 MNIST 입니다. MNIST는 뉴욕대의 Recunn 교수가 필기체 인식을 위한 알고리즘 개선을 위해 연구하는 분야로 Modified National Institute of Standards and Tech..

tsyoon.tistory.com