[code] 3단원 μ‹€μŠ΅μ½”λ“œ

μˆ˜μ • λͺ©λ‘



########## (9μͺ½) νŒ¨ν‚€μ§€ μž„ν¬νŠΈ ##########
import numpy as np



########## (10μͺ½) 평탄화, μ •κ·œν™” ##########

### ------ mnist 데이터 λ‹€μš΄λ‘œλ“œ ν•¨μˆ˜ load_mnist()μ •μ˜
def load_mnist(flatten=True, normalize = False) :
### ------ mnist λͺ¨λ“ˆ μž„ν¬νŠΈ
from tensorflow.keras.datasets import mnist
### ------ 내렀받은 데이터λ₯Ό ν›ˆλ ¨μš©, ν…ŒμŠ€νŠΈμš©μœΌλ‘œ 뢄리
(x_train, t_train), (x_test, t_test) = mnist.load_data()

### ------ μ •κ·œν™” κ³Όμ •
if normalize :
### ------ 각 값을 255둜 λ‚˜λˆ„μ–΄ 0κ³Ό 1 사이 κ°’μœΌλ‘œ λ§Œλ“¦.
x_train, x_test = x_train / 255.0, x_test / 255.0
### ----- 각 숫자λ₯Ό λΆ€λ™μ†Œμˆ˜μ μœΌλ‘œ ν‘œκΈ°
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)

### ------ 평탄화 κ³Όμ •
if flatten :
### ------ 평탄화 이전 x_train, x_test의 ν˜•νƒœ 좜λ ₯
print("<평탄화 이전 데이터 κ°œμˆ˜μ™€ ν˜•νƒœ>")
print('평탄화 이전 x_train ν˜•νƒœ ::', '개수:', x_train.shape[0], 'μ‚¬μ΄μ¦ˆ:', x_train.shape[1:])
print("평탄화 이전 x_test ν˜•νƒœ::", '개수:', x_test.shape[0], 'μ‚¬μ΄μ¦ˆ:', x_test.shape[1:])

### ------ 평탄화(μ΄λ―Έμ§€κ°œμˆ˜λŠ” κ·ΈλŒ€λ‘œ 두고 ν•œ μ€„λ‘œ λ°”κΏˆ.)
x_train = x_train.reshape(x_train.shape[0], -1)
x_test = x_test.reshape(x_test.shape[0], -1)

### ------ 평탄화 이후 x_train, x_test ν˜•νƒœ 좜λ ₯
print('')
print('<평탄화 이후 데이터 κ°œμˆ˜μ™€ ν˜•νƒœ>')
print('평탄화 이후 x_train ν˜•νƒœ::', '개수:', x_train.shape[0], 'μ‚¬μ΄μ¦ˆ:', x_train.shape[1:])
print("평탄화 이후 x_test ν˜•νƒœ::", '개수:', x_test.shape[0], 'μ‚¬μ΄μ¦ˆ:', x_test.shape[1:])

return (x_train, t_train), (x_test, t_test)

### ------ load ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜κ³  λ³€μˆ˜μ— ν• 
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize = False)




########## (11μͺ½) ν›ˆλ ¨μš© λ°μ΄ν„°μ…‹μ˜ 첫번째 데이터λ₯Ό μ΄λ―Έμ§€ν–‰λ ¬λ‘œ λ‚˜νƒ€λ‚΄κΈ° ##########

for i, x in enumerate(x_train[0]) :
### ---- xλ₯Ό 3자리 μ •μˆ˜λ‘œ ν‘œν˜„ν•˜κ³  곡백 μ‚½μž…
print(f'{x:3}', end=' ')
### ---- 28번째 μˆ«μžλ§ˆλ‹€ μ€„λ°”κΏˆ.
if (i+1)%28 == 0 :
print()



########## (12μͺ½) 인곡지λŠ₯ λͺ¨λΈ 생성 ##########

### ------ νŒ¨ν‚€μ§€ μž„ν¬νŠΈ
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt ### μ‹œκ°ν™” 도ꡬ


### --- load_mnist() ν•¨μˆ˜λ‘œ 데이터λ₯Ό λ‚΄λ €λ°›μ•„ ν›ˆλ ¨μš©, ν…ŒμŠ€νŠΈμš© λ³€μˆ˜μ— ν• λ‹Ή(μ •κ·œν™”, 평탄화 λͺ¨λ‘ μ‹œν–‰)

(train_images,train_labels),(test_images,test_labels) = load_mnist(flatten=True, normalize=True)


########## (13μͺ½) λͺ¨λΈ 생성 : λ‹€μΈ΅ νΌμ…‰νŠΈλ‘ (MLP) 생성 ##########

model = models.Sequential([
### --- 은닉측1 ꡬ성 (λ‰΄λŸ°κ°œμˆ˜ : 128, ν™œμ„±ν™”ν•¨μˆ˜ : relu)
layers.Dense(128, activation = 'relu'),
### --- 은닉측2 ꡬ성 (λͺ°λΌλ„ 됨.)
layers.Dropout(0.2),
### --- 좜λ ₯μΈ΅ ꡬ성 (λ‰΄λŸ°κ°œμˆ˜: 10개 (숫자0~9), ν™œμ„±ν™”ν•¨μˆ˜ : softmax)
### --- 은닉측을 거쳐 κ³„μ‚°λœ (이미지와 μ •μˆ˜ kκ°„ μœ μ‚¬ 정도)λ₯Ό 좜λ ₯측의 각 νΌμ…‰νŠΈλ‘  0~9둜 좜λ ₯
layers.Dense(10, activation='softmax')
])

### --- λͺ¨λΈ 컴파일(μ†μ‹€ν•¨μˆ˜, μ˜΅ν‹°λ§ˆμ΄μ €, ν‰κ°€μ§€ν‘œ μ„€μ • - 아직 λͺ°λΌλ„ 됨)
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])



########## (14μͺ½) λͺ¨λΈ ν›ˆλ ¨(κ°€μ€‘μΉ˜μ„€μ •) : ν›ˆλ ¨μš© 데이터λ₯Ό μ‚¬μš©ν•˜μ—¬ λͺ¨λΈ ν•™μŠ΅μ‹œν‚€κΈ° ##########
model.fit(train_images, train_labels, epochs=5)

### ------ λͺ¨λΈ 평가 : ν…ŒμŠ€νŠΈ λ°μ΄ν„°λ‘œ λͺ¨λΈ μ„±λŠ₯ 평
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose = 2)
print(f'\nTest Accuracy : {test_acc * 100:.2f} %')




########## (15μͺ½) 예츑 및 μ‹œκ°ν™” ##########

### ------ ν…ŒμŠ€νŠΈ μ΄λ―Έμ§€μ—μ„œ μ˜ˆμΈ‘κ°’ μ–»κΈ°
predictions = model.predict(test_images)
predicted_labels = [tf.argmax(p) for p in predictions]

### ------ 예츑 및 μ‹œκ°ν™”
plt.figure(figsize=(9,9)) # μƒˆλ‘œμš΄ κ·Έλ¦Ό 생성 및 μ‚¬μ΄μ¦ˆλ₯Ό 9*9둜 μ„€μ •
for i in range(25) : # test_images의 첫 25개 그림에 λŒ€ν•΄ μ‹œν–‰
plt.subplot(5,5,i+1)
plt.xticks([]) # xμΆ• 눈금 λΉ„ν™œμ„±ν™”
plt.yticks([]) # yμΆ• 눈금 λΉ„ν™œμ„±ν™”
plt.grid(False) # κ·Έλ¦¬λ“œ λΉ„ν™œμ„±ν™”
plt.imshow(test_images[i].reshape(28,28), cmap = plt.cm.binary) # 이미지 리슀트λ₯Ό 이진색상 그림으둜 ν‘œμ‹œ
plt.xlabel(f"real : {test_labels[i]} - predict : {predicted_labels[i]}") # μ‹€μ œκ°’, μ˜ˆμΈ‘κ°’ ν‘œμ‹œ

plt.show() # 화면에 λ‚˜νƒ€λ‚΄κΈ°