본문 바로가기

Study/class note

딥러닝 / 텐서플로우로 신경망 구현하기

7 텐서플로우로 2층 신경망 구현하기 - p.137

필기체 데이터를 학습 시키는 2층 신경망을 책과 똑같이 구성

#1. 필요한 패키지를 불러옵니다
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import numpy as np

tf.random.set_seed(777)

#2. 모델 구성
model = Sequential()
model.add(Flatten(input_shape=(784,)))  #입력층(0층)
model.add(Dense(100,activation = 'sigmoid'))  #은닉층(1층)
model.add(Dense(10,activation = 'softmax'))  #출력층(2층)


#3. 입력 데이터 만들기
from tensorflow.keras.datasets.mnist import load_data
(x_train,y_train), (x_test,y_test) = load_data(path='mnist.npz') 


# 3차원 -> 2차원으로 변경하면서 정규화 작업 수행
x_train = x_train.reshape(60000,28*28)
x_test = x_test.reshape(10000, 28*28)

x_train = x_train/255.0
x_test = x_test/255.0

#4. 정답데이터 만들기
from tensorflow.keras.utils import to_categorical

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

#5. 모델 설정
model.compile(optimizer = 'adam',  #경사하강법
              loss = 'categorical_crossentropy',  #오차함수
              metrics = ['acc'])  

#6. 모델 훈련
model.fit(x_train,y_train, epochs = 30, batch_size = 100)

#7. 모델 평가
model.evaluate(x_test,y_test, verbose = 0)  #[0.07463686168193817, 0.977400004863739]

 

 

문제74. fashion mnist 데이터 셋 불러오기.

import matplotlib.pyplot as plt
from tensorflow.keras.datasets.fashion_mnist import load_data

(x_train, y_train), (x_test, y_test) = load_data()

target_dict = {
 0: 'T-shirt/top',
 1: 'Trouser',
 2: 'Pullover',
 3: 'Dress',
 4: 'Coat',
 5: 'Sandal',
 6: 'Shirt',
 7: 'Sneaker',
 8: 'Bag',
 9: 'Ankle boot',
}

plt.figure(figsize=(10,10))

for i in range(0,20):
    plt.subplot(5,5, i+1)
    plt.imshow(x_train[i] )
    plt.title( target_dict[(y_train[i]) ])
    plt.xticks([])
    plt.yticks([])

 

 

문제75. 우리가 텐서플로우로 만든 4장의 2층 신경망에 fashion mnist 데이터를 넣고 학습 시키고 테스트 데이터의 정확도를 출력하시오.

#1. 필요한 패키지를 불러옵니다
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import numpy as np

tf.random.set_seed(777)

#2. 모델 구성
model = Sequential()
model.add(Flatten(input_shape=(784,)))  #입력층(0층)
model.add(Dense(100,activation = 'sigmoid'))  #은닉층(1층)
model.add(Dense(10,activation = 'softmax'))  #출력층(2층)


#3. 입력 데이터 만들기
from tensorflow.keras.datasets.fashion_mnist import load_data

(x_train, y_train), (x_test, y_test) = load_data()  #(60000, 28, 28)


# 3차원 -> 2차원으로 변경하면서 정규화 작업 수행
x_train = x_train.reshape(60000,28*28)
x_test = x_test.reshape(10000, 28*28)

x_train = x_train/255.0
x_test = x_test/255.0

#4. 정답데이터 만들기
from tensorflow.keras.utils import to_categorical

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

#5. 모델 설정
model.compile(optimizer = 'adam',  #경사하강법
              loss = 'categorical_crossentropy',  #오차함수
              metrics = ['acc'])  

#6. 모델 훈련
model.fit(x_train,y_train, epochs = 30, batch_size = 100)

#7. 모델 평가
model.evaluate(x_test,y_test, verbose = 0)  #[0.3197975754737854, 0.888700008392334]

 

 

문제76. (오늘의 마지막 문제) 위의 테스트 데이터의 정확도를 90%을 넘길 수 있도록 층수와 뉴런의 갯수를 조정하시오.

(하이퍼 파라미터는 다 만져도 됩니다)

1. 아나콘다 프롬프트 창에서 keras tuner 설치

pip install keras-tuner

#1. 필요 패키지 로드
from tensorflow.keras.datasets.fashion_mnist import load_data  # fashion 데이터 로드
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import numpy as np
######튜닝에 필요한 패키지
import IPython
from kerastuner import HyperModel
import kerastuner as kt
from tensorflow import keras

tf.random.set_seed(777) 


#2. 입력 데이터 로드 - 정규화 작업 수행
(x_train, y_train), (x_test, y_test) = load_data()  #(60000, 28, 28)

x_train = x_train/255.0
x_test = x_test/255.0


#3. 모델 생성
def model_builder(hp):
    model = Sequential()  #모델생성
    model.add(Flatten(input_shape=(28,28)))  #입력층 (,784)로 flatten
    
    # 첫번째 Dense 레이어 128~512까지 32스탭씩 노드 수 조정
    hp_units1 = hp.Int('units1', min_value=128, max_value=512, step = 32)  
    model.add(Dense(units=hp_units1, activation='relu'))  #은닉1층
    model.add(Dense(10,activation = 'softmax'))  #출력층(2층)
    
    model.compile(optimizer='adam',    #학습률 옵션 제외
                 loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                 metrics=['accuracy'])
    
    return model


#4. tuner 생성
tuner=kt.Hyperband(model_builder,
                     objective = 'val_accuracy',  
                     max_epochs = 10,
                     seed = 20,  # 시드값
                     overwrite=True)  #상세로그 비활성화



#5. 하이퍼파라미터 검색을 실행하기 전에 훈련 단계가 끝날 때마다 훈련 결과를 지우도록 콜백 설정
class ClearTrainingOutput(tf.keras.callbacks.Callback):
    def on_train_end(*args, **kwargs):
        IPython.display.clear_output(wait = True)
        
        
#6. 하이퍼 파라미터 검색
tuner.search(x_train, y_train, epochs = 10,
             validation_data = (x_test, y_test), callbacks = [ClearTrainingOutput()])


#7. 최적의 파라미터 찾기
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print('첫번째 Dense 노드 수: %s'%best_hps.get('units1'))     #여기까지 코드블럭 한번 끊기

#8. best parameter로 모델 생성
model = tuner.hypermodel.build(best_hps)
model.fit(x_train, y_train, epochs = 150, batch_size = 300,
         validation_data = (x_test, y_test))

#9. 모델 평가
model.evaluate(x_test,y_test)    #[0.7374008893966675, 0.900600016117096]

반응형