본문 바로가기

프로그래밍/for AI

[DL] 딥러닝 기초개념 정리

딥러닝을 위한 가장 기본적인 코드들

https://en.wikipedia.org/wiki/Rectifier_(neural_networks)

1. tips2.csv 데이터 가공 및 불러오기

import seaborn as sns
from sklearn.preprocessing import LabelEncoder
tips = sns.load_dataset('tips')

tips.sex.replace(['Female', 'Male'], [0,1], inplace=True) # 성별 남/여-> 1, 0
tips.smoker.replace(['No', 'Yes'], [0,1], inplace=True) # 흡연 유/무 -> 1, 0
tips.time.replace(['Dinner', 'Lunch'], [1,0], inplace=True) # 점심/저녁 -> 1, 0
le = LabelEncoder()
tips.day = le.fit_transform(tips.day) # 라벨인코딩: 요일정보 -> 숫자(0,1,...)
tips.to_csv('tips2.csv', index=False) # csv file로 저장
tips2 = pd.read_csv('tips2.csv') # 읽어오기

@ 핵심: 모델 학습에 사용될 수 있도록 범주형 변수들의 값을 숫자로 바꿔준다. (값의 종류가 3개 이상일 때 라벨인코딩)

tips2.csv

 

2. 회귀모델 X, y 나누기 (X=feature, y=label)

X = tips2.drop('tip', axis=1) # 데이터에서 [tip] 열만 제거
y = tips2['tip']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 )
# test_size=0.2 => train:test = 8:2

@ 핵심 : y값은 예측을 하려는 feature이다. 

 

3. 딥러닝 모델링: DNN 구현

@ DNN: Deep Neural Network, 여러개의 hiddent layer을 가진 인공신경망으로 가중치와 활성화 함수로 연결됨.

## 딥러닝 기본 템플릿(구조)##

model = Sequential()
model.add(Dense(4, input_shape=(3,), activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(4, activation='relu'))
model.add(Dense(1m activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])
history = model.fit(X_train, y_train, validation_data = [X_test, y_test],
			epochs = 40, batch_size =10)
Sequential() 레이어를 순차적으로 쌓는 딥러닝 모델 구조. activation  입력받은 신호를 변환할 때 사용된 함수
Dense(k, ) 층이 k개인 layer를 뉴런 간 완전 연결로 구성 loss 손실함수, 예측값과의 오차를 구하는 함수
Dropout(0.2) 출력의 20%를 0으로.(overfitting방지)   optimizer loss의 최소값을 찾아가는 알고리즘
model.add 구성된 layer를 모델에 추가 metrics 평가지표; acc(accuracy), mae, mse
model.compile 모델 학습을 위한 기본 설정 정의 epochs=n 전체 데이터셋을 n번 반복 학습
model.fit 모델을 학습하는 메서드 batch_size 학습에 사용하는 데이터의 묶음 크기
model checkpoint Keras 모델 학습 중 가중치 저장 및 모델 선택 Early stopping 콜백함수로, 적절한 시점에 학습을 종료시킴

@ 중요: 데이터의 크기 또는 유형에 맞게 activation function(활성함수)과 loss function(손실함수)을 선택해야 한다. 

 

4. DNN 모델 비교 : 분류 vs 회귀 

## 회귀 혹은 분류 결정에서 사용되는 손실, 활성 함수 ## (완벽히 암기)

  회귀(Regression) 분류(Classification)
출력값(output=y) 연속적인 값(실수) 범주형 값(클래스, 정수)
예시 주가 예측 성별 분류(이진), 학점 분류(다중)
활성함수(activation function) Linear, none, relu(y=x,x>=0) sigmoid(이진), softmax(다중), relu
손실함수(loss function) mean_squared_error (MSE),
mean_absolute_error (MAE)
binary_crossentropy(이진),
categorical_crossentropy(다중-원핫인코딩 레이블),
sparse_categorical_crossentropy(다중-정수 레이블)
평가지표(evaluation metrics) RMSE, R2 Score Accuracy, Precision, Recall, F1 Score

@ 분류 결정에서 이진분류는 아웃풋이 1개, 다중분류는 아웃풋이 2개 이상 일때 사용한다. 

 

## 사용되는 함수 및 지표 정의 확인

activation function loss function evaluation metrics
Linear 선형 함수, 회귀 MSE 평균 제곱 오차, 회귀 RMSE MSE 제곱근, 회귀
relu 0 이하는 0, 양수는 그대로, 딥러닝 MAE 평균 절대 오차, 회귀 R2 Score 결정 계수, 회귀 성능
sigmoid 0~1 확률 변환, 이진 분류 binary_crossentropy 이진 분류 손실 Accuracy 전체 정확도, 분류
softmax 확률 분포 변환, 다중 분류 categorical_crossentropy 다중 분류 손실 (원-핫) Precision 정밀도, 양성 예측 정확도
    sparse_categorical_crossentropy 다중 분류 손실 (정수 라벨) Recall 재현율, 양성 탐지율
        F1 Score Precision-Recall 조화 평균

 

## 데이터 불러오기 (결측치 처리 등 데이터 전처리 된 데이터) 

https://www.kaggle.com/datasets/hnazari8665/tipscsv/data 

 

tips.csv

 

www.kaggle.com

import pandas as pd
tips = pd.read_csv('tips2.csv')
tips.head()

 

 

5. 예시 코드

- 회귀모델 예시: total_bill 외의 다른 features를 가지고 total_bill의 값을 예측하는 것

-  분류모델 예시: smoker외 다른 features를 가지고 smoker 유부를 예측하는 것

 

## 회귀 모델 예시 코드

-> y: 'total_bill'로 총 계산 요금의 값이다. 회귀 예측을 위한 수치형 데이터 이다. 

@중요:  loss = 'mse' / metrics = 'mse', 'mae' / output layer activation = 'linear' or None

# 필요 모듈 불러오기
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

# 데이터 세팅
X = tips.drop('total_bill', axis=1)
y = tips['total_bill']
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=41 )
X_train.shape, X_test.shape, y_train.shape, y_test.shape # ((195, 6), (49, 6), (195,), (49,))

# Sequential 모델 생성
model = Sequential()
model.add(  Dense( 6, activation='relu', input_shape=(6,)  )  )
model.add(  Dense( 4, activation='relu',  )  )
model.add(  Dense( 1, activation='linear'  )  )

# 컴파일, 콜백함수 설정, 모델 학습
model.compile(  loss='mse', optimizer='adam', metrics=['mse', 'mae']  )
es = EarlyStopping( monitor='val_loss' , patience=3 , verbose=1 )
mc = ModelCheckpoint( 'best_model.h5', monitor='val_loss', save_best_only=True, verbose=1  )
history = model.fit(  X_train , y_train, epochs=50, batch_size=8, validation_data=(X_test, y_test) , callbacks=[es, mc] )

# DNN 모델을 활용해서 시뮬레이션 데이터 예측하기
simul = [3.23, 1. , 0. , 2. , 1. , 2. ]
model.predict([ simul ]) # array([[20.120998]], dtype=float32)

 

## 분류 모델 예시 코드

-> y: 'smoker'의 값으로 1or0(True/False) 범주형 변수이다. 분류모델의 예측값(결과)로 사용된다.

@중요:  loss = 'binary_crossentropy' / metrics  = 'accuracy' / output layer activation= 'sigmoid'

# 필요한 모듈 불러오기
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

# 데이터 설정
X = tips.drop('smoker', axis=1)
y = tips[ 'smoker' ]
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=41 )
X_train.shape, X_test.shape, y_train.shape, y_test.shape

# 데이터 정규화
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 시퀀스 모델 구조 생성
model = Sequential()
model.add(Dense(6, activation='relu', input_shape=(6,)))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# 모델 학습 기본값 설정 및 학습
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
es = EarlyStopping(monitor='val_loss', patience=10, verbose=1)
mc = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
history = model.fit(X_train, y_train, epochs=50, batch_size=8, validation_data=(X_test, y_test), callbacks=[es, mc])

# DNN 모델을 활용해서 시뮬레이션 데이터 예측하기
simul = [23.33,  5.65,  1.  ,  2.  ,  1.  ,  2.  ]
model.predict([ simul ])