소품집

[KT AIVLE] keras Sequential model - DL 기본 본문

AI/KT 에이블스쿨

[KT AIVLE] keras Sequential model - DL 기본

sodayeong 2022. 9. 17. 01:07

sequential model 기본

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.metrics import *
from sklearn.preprocessing import StandardScaler, MinMaxScaler

# DL - keras
from keras.models import Sequential # 모델 레이어를 선형으로 연결, 인스턴스 자동으로 넘겨줌
from keras.layers import Dense # hidden layer 쌓기
from tensorflow.keras.optimizers import Adam # 옵티마이저 설정을 위해서
model = Sequential([
    Dense(32, input_shape=(784,)),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
])

Sequential 모델은 레이어를 선형으로 연결하고, 인스턴스를 다음 층 레이어에 넘겨주면서 모델을 구성할 수 있음.

model = Sequential()
layer1 = Dense(32, input_shape=(784,), activation='relu')
model.add(layer1)

.add() 메소드로 레이어를 쌓으며 층을 늘릴 수 있음

입력 형태 선언

첫 번째 선언한 Sequential 모델 레이어를 기준으로 입력 형태 정보(input shape, dense, activation 등)를 받음.
두 번째 이후 레이어는 앞서 선언한 정보를 받아오기 때문에 또 입력해줄 필요 없음.
* input_shape =(784,) = input_dim=784 는 동치

컴파일

모델 학습 이전, compile 메소드로 학습 방식에 대한 설정을 해야함.
1) 정규화 (optimizer) > adam, learning rate 옵션으로 최적값 찾기
2) 손실 함수 (loss function) 모델 최적화를 위한 목적 함수
3) 기준(metric) 리스트 > 분류 문제에서는 accuracy로 설정

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
              
# For custom metrics
import keras.backend as K

def mean_pred(y_true, y_pred):
    return K.mean(y_pred)

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


학습

# model 선언
model = Sequential()
layer1 = Dense(32, activation='relu', input_shape=(100,))
layer2 = Dense(1, activation='sigmoid')

# layer add
model.add(layer1)
model.add(layer2)

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

# Generate dummy data
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)

fit() 함수로 epochs, batch size, 데이터 분리(7:3 or 8:2) 등 옵션을 선언하고 위 만든 모델을 학습하게 된다.



https://sodayeong.tistory.com/category/Deep%20Learning

'Deep Learning' 카테고리의 글 목록

DB, 클라우드, 데이터분석을 공부합니다 - 시간내서 하지말고 아무때나 하자

sodayeong.tistory.com

작년 딥러닝 전공 과목 수강 할 때 로깅한 기록인데 내거 보고 참고 많이 했따.. 뿌듯

728x90
Comments