728x90

인공 신경망

 

패션 MNIST

딥러닝에서 MNIST가 유명함 -> 손으로 쓴 0~9까지 숫자 자료. 패션 MNIST는 숫자 대신 패션 아이템으로 이루어짐

from tensorflow import keras

(train_input, train_target), (test_input, test_target) = keras.datasets.fashion_mnist.load_data()

60,000개의 28*28 이미지로 되어 있음

print(train_input.shape, train_target.shape)
print(test_input.shape, test_target.shape)

(60000, 28, 28) (60000,)

(10000, 28, 28) (10000,)

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 10, figsize=(10,10))
for i in range(10):
    axs[i].imshow(train_input[i], cmap='gray_r')
    axs[i].axis('off')
plt.show()

print([train_target[i] for i in range(10)])

[9, 0, 0, 3, 0, 2, 7, 2, 5, 5]

패션 아이템의 종류를 나타내고 있다. 종류는 아래와 같다

label item
0 티셔츠
1 바지
2 스웨터
3 드레스
4 코트
5 샌들
6 셔츠
7 스니커즈
8 가방 
9 앵클부츠
import numpy as np

print(np.unique(train_target, return_counts=True))

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8), array([6000, 6000, 6000, 6000, 6000, 6000, 6000, 6000, 6000, 6000]))

label별로 item이 몇개씩 있는지 확인했고, 각 60000개씩 있는 것을 볼 수 있다.

 

로지스틱 회귀로 패션 아이템 분류하기

훈련 샘플이 6만개라 전체를 한꺼번에 하기보다는 하나씩 꺼내서 모델을 훈련하는 것이 좋다.

이럴 때 사용하는 것이 확률적 경사 하강법(SGDClassifier)

train_scaled = train_input / 255.0
train_scaled = train_scaled.reshape(-1, 28*28)
print(train_scaled.shape)

(60000, 784)

train_scaled = train_input / 255.0 
이 부분이 중요한데, 각 pixel이 0~255의 정수값을 가지는 값이다. 머신러닝에서 효율적으로 사용하기 위해 이 값을 0~1사이의 실수로 변경하여 정규화 시켜준다. 이를 위해 최대값으로 나누는 작업을 한다.
 
from sklearn.model_selection import cross_validate
from sklearn.linear_model import SGDClassifier

sc = SGDClassifier(loss='log', max_iter=5, random_state=42)

scores = cross_validate(sc, train_scaled, train_target, n_jobs=-1)
print(np.mean(scores['test_score']))

0.8195666666666668

max_iter=5는 SGDClassifier 반복 횟수

 

인공신경망

텐서플로와 케라스

import tensorflow as tf
from tensorflow import keras

인공신경망으로 모델 만들기

from sklearn.model_selection import train_test_split

train_scaled, val_scaled, train_target, val_target = train_test_split(
    train_scaled, train_target, test_size=0.2, random_state=42)

print(train_scaled.shape, train_target.shape)
print(val_scaled.shape, val_target.shape)

(48000, 784) (48000,)

(12000, 784) (12000,)

dense = keras.layers.Dense(10, activation='softmax', input_shape=(784,))
model = keras.Sequential(dense)

인공신경망으로 패션 아이템 분류하기

model.compile(loss='sparse_categorical_crossentropy', metrics='accuracy')
print(train_target[:10])

[7 3 5 8 6 9 3 3 9 9]

model.fit(train_scaled, train_target, epochs=5)
Epoch 1/5
1500/1500 [==============================] - 3s 2ms/step - loss: 0.6097 - accuracy: 0.7913
Epoch 2/5
1500/1500 [==============================] - 2s 2ms/step - loss: 0.4785 - accuracy: 0.8396
Epoch 3/5
1500/1500 [==============================] - 2s 2ms/step - loss: 0.4557 - accuracy: 0.8479
Epoch 4/5
1500/1500 [==============================] - 2s 2ms/step - loss: 0.4438 - accuracy: 0.8519
Epoch 5/5
1500/1500 [==============================] - 2s 2ms/step - loss: 0.4362 - accuracy: 0.8547
<keras.callbacks.History at 0x7f253d669550>

결과가 할 때마다 다르게 나온다. 그러나 충분히 안정적으로 된다면 차이가 크지 않다.

model.evaluate(val_scaled, val_target)
375/375 [==============================] - 1s 1ms/step - loss: 0.4475 - accuracy: 0.8494
[0.44751664996147156, 0.8494166731834412]
728x90

+ Recent posts