딥러닝 복습
notmnist
!wget http://yaroslavvb.com/upload/notMNIST/notMNIST_small.mat
import matplotlib.pyplot as plt
from scipy import io
import numpy as np
data = io.loadmat('notMNIST_small.mat')
data
resolution = 28
classes = 10
x = np.transpose(x, (2, 0, 1))
print(x.shape)
x = x.reshape( (-1, resolution, resolution, 1) )
from sklearn.model_selection import train_test_split
train_x , test_x , train_y , test_y = train_test_split(x,y,random_state = 2023 ,test_size=0.2)
train_x.shape , train_y.shape , test_x.shape , test_y.shape
max_n , min_n = train_x.max() , train_x.min()
train_x = (train_x - min_n) /( max_n - min_n)
test_x = (test_x - min_n) / (max_n - min_n)
from tensorflow.keras.utils import to_categorical
class_n=len(np.unique(train_y))
train_y = to_categorical(train_y , class_n)
test_y = to_categorical(test_y , class_n)
import tensorflow as tf
from tensorflow import keras
from keras.src.engine.training import optimizer
keras.backend.clear_session()
il = keras.layers.Input(shape = [28,28,1])
hl = keras.layers.Flatten()(il)
hl = keras.layers.Dense(256,activation = 'relu')(hl)
hl = keras.layers.Dense(256,activation = 'relu')(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = keras.layers.Dropout(0.2)(hl)
hl = keras.layers.Dense(128,activation = 'relu')(hl)
hl = keras.layers.Dense(128,activation = 'relu')(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = keras.layers.Dropout(0.2)(hl)
hl = keras.layers.Dense(64,activation = 'relu')(hl)
hl = keras.layers.Dense(64,activation = 'relu')(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = keras.layers.Dropout(0.2)(hl)
ol = keras.layers.Dense(10 , activation = 'softmax')(hl)
model = keras.models.Model(il , ol)
model.compile(optimizer = 'adam' , loss = keras.losses.categorical_crossentropy,metrics = ['accuracy'])
model.summary()
from tensorflow.keras.callbacks import EarlyStopping
es = EarlyStopping(monitor = 'val_loss',
patience=10 ,
min_delta= 0 ,
verbose=1,
restore_best_weights=True
)
model.fit(train_x , train_y ,
epochs = 100000 ,
verbose = 1 ,
validation_split = 0.2,
callbacks = [es]
)
model.evaluate(test_x , test_y)
y_pred = model.predict(test_x)
y_pred_arg = np.argmax(y_pred , axis = 1)
test_y_arg = np.argmax(test_y , axis = 1)
from sklearn.metrics import accuracy_score , classification_report
accuracy_score(test_y_arg , y_pred_arg)
print(classification_report(test_y_arg , y_pred_arg))
letters_str = "ABCDEFGHIJ"
rand_idx = np.random.randint(0, len(y_pred_arg))
test_idx = test_y_arg[rand_idx]
pred_idx = y_pred_arg[rand_idx]
class_prob = np.floor( y_pred[rand_idx]*100 )
print(f'idx = {rand_idx}')
print(f'해당 인덱스의 이미지는 {letters_str[test_idx]}')
print(f'모델의 예측 : {letters_str[pred_idx]}')
print(f'모델의 클래스별 확률 : ')
print('-------------------')
for idx, val in enumerate(letters_str) :
print(val, class_prob[idx])
print('=================================================')
if test_y_arg[rand_idx] == y_pred_arg[rand_idx] :
print('정답')
else :
print('땡')
plt.imshow(test_x[rand_idx], cmap='Greys')
plt.show()
temp = (test_y_arg == y_pred_arg)
false_idx = np.where(temp==False)[0]
false_len = len(false_idx)
false_len
letters_str = "ABCDEFGHIJ"
rand_idx = false_idx[np.random.randint(0, false_len)]
test_idx = test_y_arg[rand_idx]
pred_idx = y_pred_arg[rand_idx]
class_prob = np.floor( y_pred[rand_idx]*100 )
print(f'idx = {rand_idx}')
print(f'해당 인덱스의 이미지는 {letters_str[test_idx]}')
print(f'모델의 예측 : {letters_str[pred_idx]}')
print(f'모델의 클래스별 확률 : ')
print('-------------------')
for idx, val in enumerate(letters_str) :
print(val, class_prob[idx])
print('=================================================')
if test_y_arg[rand_idx] == y_pred_arg[rand_idx] :
print('정답')
else :
print('땡')
plt.imshow(test_x[rand_idx], cmap='Greys')
plt.show()