Languages/python

[PYTHON]tensorflow/keras mnist 필기체인식 기초 예제

뱅타 2021. 3. 29. 22:22

 

tensorflow를 조금 더 쉽게 사용하기 위해서 keras가 나왔다.

자세한 내용은 초보라서...

지금은 그냥 그렇다고 알고만 있기.

 

사용하기에 앞서 세가지 라이브러리 설치하기

$pip install pydot
$pip install tensorflow
$pip install keras

 

pydot의 경우 이렇게 쓰면 된다는데 여기서는 안써봄

출처 : https://m.blog.naver.com/PostView.nhn?blogId=dic1224&logNo=221239472060&proxyReferer=https:%2F%2Fwww.google.com%2F

 

이렇게 하나씩 깔기!

내장되어 있는 기본 코드 작성

# 필요한 라이브러리 불러오기
from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical

# MNIST 데이터셋 불러오기
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 이미지 데이터 준비하기 (모델에 맞는 크기로 바꾸고 0과 1사이로 스케일링)
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

# 레이블을 범주형으로 인코딩
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# 모델 정의하기 (여기에서는 Sequential 클래스 사용)
model = models.Sequential()
model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
model.add(layers.Dense(10, activation='softmax'))

# 모델 컴파일 하기
model.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])

# fit() 메서드로 모델 훈련 시키기
model.fit(train_images, train_labels, epochs=5, batch_size=128)

# 테스트 데이터로 정확도 측정하기
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('test_acc: ', test_acc)

실행하면 이렇게 결과 출력.

 

데이터 갯수 보기.

# MNIST 데이터셋 불러오기
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(len(train_images))
print(len(train_labels))
print(len(test_images))
print(len(test_labels))

 

60000은 train시키기. 10000은 test하기.

print(train_images[1])하면

그냥 출력 해 보면

이렇게 이상하게 짤려서 나옴.

 

데이터 이쁘게 한번 보기

arr2D = train_images[1]

for i in arr2D :
    print()
    for j in i :
        print(j, end="\t")

그래도 이상하게 보이니

데이터 값들을 0과 1로 추려보기

for i in arr2D :
    print()
    for j in i :
        if j == 0:
            print("0", end="")
        else : 
            print("1", end = "")

결과 ... 좀 더 머 알아보기 쉽다.

0000000000000001111100000000 0000000000000011111100000000 0000000000000111111111000000 0000000000011111111111000000 0000000000011111111111000000 0000000000111111111111000000 0000000001111111110011100000 0000000011111100000011100000 0000000111111100000011100000 0000000111100000000011100000 0000000111000000000011100000 0000001111000000000011100000 0000001111000000001111100000 0000001110000000011111000000 0000001110000000111100000000 0000001110000001111000000000 0000001111111111111000000000 0000001111111111100000000000 0000001111111110000000000000 0000000111111100000000000000 0000000000000000000000000000

 

  • 깨알 콘솔창에서 값들이 잘리면 콘솔창 우클릭 후 버퍼 사이즈를 크게 늘려주면 안잘리게 나온다

 

사진의 크기가 28*28이니 reshape으로 설정을 맞춰 준다.

 

모델 안에 넣어서 테스트 해 보기.

 

9 * 10의 -2승 = 0.09

3 * 10의 -1승 = 0.3

앞보다 뒤의 숫자를 보아야한다.

결과는 7

 

  • 알아서 가장 배열 중 가장 큰 숫자 뽑기
import numpy as np
a = [0,0,4,0,0,
     0,0,0,0,0]
a_n = np.array(a)

# 배열의 가장 큰 값을 불러오는 매서드
pred = np.argmax(a_n)

print(pred)

 

 

728x90
반응형