[딥러닝] 7장 MLP-2

2024. 12. 6. 00:21·etc

고수준 딥러닝 프레임워크 케라스  

->  핵심 데이터 구조 = model은 레이어를 구성하는 방법을 나타낸다.

 

1) Sequantial 모델을 만들고 모델에 필요한 레이어를 추가하는 방법

import matplotlib.pyplot as plt
import tensorflow as tf

model = tf.keras.models.Sequential()

model.add(tf.keras.layers.Dense(units=2, input_shape=(2,), activation='sigmoid')) 
model.add(tf.keras.layers.Dense(units=1, activation='sigmoid')) # 출력층, 1개의 뉴런

model.complie(loss='mean_squared_error', optimizer= keras.optimizers.SGD(lr=0.3)) #compile()함수 호출하여 Sequential 모델 컴파일한다

model.fit(X, y, batch_size=1, epochs= 10000) #입략, 타겟, 배치크기 설정, 데이터셋 10000번 학습

print(model.predict(X))

 

 

2) 함수형 API를 사용하는 방법

inputs= Input(shape=(2,)) #2차원
x=Dense(2, activation="sigmoid")(inputs)
prediction=Dense(1, activation="sigmoid")(x)

model=Model(inputs= inputs, outputs= prediction)

 

 

3) Model 클래스를 상속받아서 클래스를 정의하는 방법

 

 

MNIST 데이터 

1) 숫자 데이터 가져오기

2) 신경망 모델 구축하기

model= tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(512, activation='relu', input_shape=(784,)))
model.add(tf.keras.layers.Dense(10, activation='sigmoid'))

3) 옵티마이저와 손실함수, 지표 등을 정의하는 컴파일 단계

model.compile(optimizer='rmsprop', loss='mse', metrics=['accuracy'])

 

- 손실함수(loss function) : 신경망의 출력과 정답 간의 오차를 계산하는 함수

- 옵티마이저(optimizer): 손실 함수를 기반으로  신경망의 파라미터를 최적화하는 알고리즘

 

4) 데이터 전처리

5) 정답 레이블 형태 변경 (원핫 인코딩)

# 클래스를 학습에 이용하기 위해 데이터 가공
train_labels= tf.keras.utils.to_categorical(train_labels)
test_labels= tf.keras.utils.to_categorical(test_labels)

 

to_categorical()

0,1 값으로 저장해야 원활한 데이터 처리가 가능하기 떄문에 변

 

 

6) 학습

model.fit(train_images, train_labels, epochs=5, batch_size=128)

 

7) 테스트

test_loss, test_acc = model.evaluate(test_images, test_labels)
print('테스트 정확도:', test_acc)

 

 

 

 

텐서

- 다차원 넘파이 배열

- 배열의 차원을 축이라고 부름 (3차원 텐서에는 3개의 축이 있음, ndim 속성)

 

 

▌compile(optimizer, loss=None, metrics=None): 훈련을 위해서 모델을 구성하
는 메소드
▌fit(x=None, y=None, batch_size=None, epochs=1, verbose=1): 훈련 메소드
▌evaluate(x=None, y=None): 테스트 모드에서 모델의 손실 함수 값과 측정 항
목 값을 반환
▌predict(x, batch_size=None): 입력 샘플에 대한 예측값을 생성
▌add(layer): 레이어를 모델에 추가한다

 

 

하이퍼 매개변수

- 학습률이나 모멘텀의 가중치, 은닉층의 개수, 유닛의 개수, 미니 배치의 크기

 

하이퍼 매개변수에 대해 몇개의 값을 지정하면 가장 좋은 조합을 찾아주는 알고리즘 

그리드 검색

import numpy as np 
import matplotlib.pyplot as plt 
import tensorflow as tf
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier


# 데이터 세트 준비
(train_images, train_labels), (test_images, test_labels) = 
tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape((60000, 28 * 28)) # 총 개수 60000개, 28*28 픽셀
train_images = train_images.astype('float32') / 255 # 0,1 범위 정규화
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
train_labels = tf.keras.utils.to_categorical(train_labels) #원핫 인코딩
test_labels = tf.keras.utils.to_categorical(test_labels)


# 신경망 모델 구축
def build_model():
 network = tf.keras.models.Sequential()
 network = tf.keras.models.Sequential()
 network.add(tf.keras.layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
 network.add(tf.keras.layers.Dense(10, activation='sigmoid'))
 network.compile(optimizer='rmsprop',
 loss='categorical_crossentropy',
 metrics=['accuracy'])
 return network


# 하이퍼 매개변수 딕셔너리
param_grid = {
 'epochs':[1, 2, 3], # 에포크 수: 1, 2, 3
 'batch_size':[32, 64]
 }


# 케라스 모델을 sklearn에서 사용하도록 포장한다. 
model = KerasClassifier(build_fn= build_model, verbose=1)

# 그리드 검색
gs= GridSearchCV(
 estimator=model,
 param_grid=param_grid, 
cv=3, 
n_jobs=-1 
)


# 그리드 검색 결과 출력
grid_result= gs.fit(train_images, train_labels)
 print(grid_result.best_score_)
 print(grid_result.best_params_

 

그리드 검색을 활용해서 최적의 값을 검색할 수 있다.

'etc' 카테고리의 다른 글

[딥러닝] 12장 자연어 처리  (0) 2024.12.08
[딥러닝] 11장 순환신경망  (2) 2024.12.08
[딥러닝] 10장 영상인식  (1) 2024.12.07
[딥러닝] 9장 CNN  (2) 2024.12.07
[딥러닝] 8장 심층신경망  (0) 2024.12.06
'etc' 카테고리의 다른 글
  • [딥러닝] 11장 순환신경망
  • [딥러닝] 10장 영상인식
  • [딥러닝] 9장 CNN
  • [딥러닝] 8장 심층신경망
zioni
zioni
  • zioni
    jiwon's dev.log
    zioni
  • 전체
    오늘
    어제
    • 분류 전체보기 (76) N
      • spring & java (13)
      • Algorithm (14) N
      • PS (37)
      • project (3)
      • experience (1)
      • etc (6)
      • study (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    백준
    java
    백준2525
    자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
zioni
[딥러닝] 7장 MLP-2
상단으로

티스토리툴바