관리 메뉴

DeseoDeSeo

[Deep Learning] 딥 러닝 모델링( 모델 구조 설계 ) 본문

Deep Learning

[Deep Learning] 딥 러닝 모델링( 모델 구조 설계 )

deseodeseo 2023. 9. 19. 21:33

➤ 딥러닝 모델 불러오기

     ✔ 텐서플로우 안에 있는 keras

from tensorflow.keras.models import Sequential # 모델의 뼈대
# 신경망의 구성요소( 하나씩 조립)
from tensorflow.keras.layers import InputLayer, Dense, Activation
 InputLayer: 입력
 Dense : 밀집도
 Activation :활성화함수
 <  딥러닝 모델 설계 순서 >
  1. 신경망 구조 설계
  2. 신경망 학습 및 평가 방법 설정
  3. 학습
  4. 예측 및 평가
# 1. 신경망 구조 설계
# 뼈대 생성
model = Sequential()
# 입력층
model.add(InputLayer(input_shape=(1,))) #입력 특성의 개수를 작성(= 문제데이터는 1개) (studytime 1개)
# 중간층(은닉층) ➜ 활성화함수 !! 역치라는 개념을 모방하기 위해서 !
model.add(Dense(units=10)) # 뉴런 10개를 연결 ➜ 학습의 능력을 결정
model.add(Activation('sigmoid')) #활성화 함수 : 인간을 모방하기 위함( 위 선형함수와 짝궁)
# 출력층
model.add(Dense(units=1)) #예측할 데이터의 형태, 우리가 현재 예측할 데이터는 성적데이터 1개 이기에 units=1이다.

 

2. 학습 및 평가 방법 설정
    : 
딥러닝 모델은 학습법과 평가법을 지정해주어야한다!
from sklearn import metrics
model.compile(loss='mean_squared_error', # 모델의 잘못된 정도(오차) 측정 알고리즘
              optimizer='SGD', #확률적 경사하강법, #모델의 w,b 값을 최적화하는 알고리즘
              metrics = ['mse']
              )

 

3. 모델 학습
h1 = model.fit(X_train,y_train, validation_split=0.2, #교차검증을 위한 데이터 남겨두기.
          epochs=20) #모델의 최적화 (업데이트 횟수 = 반복횟수)
#h1변수에 담는 이유 : 로그를 출력하여 패턴을 확인하기 위함.

 

4.모델 평가
model.evaluate(X_test, y_test)
#오차값은 24정도이다.

 

모델학습 로그 출력

5. 모델학습 시각화
plt.figure(figsize=(10,5))
plt.plot(h1.history['loss'],label='train_loss')
plt.plot(h1.history['val_loss'], label='val_loss')
plt.legend() # 범례
plt.show()

○ 점점 loss값이 줄어들고 있다.
○ 일반화는 val_loss를 통해서 알 수 있다. 과대적합이 아닌것을 알 수 있다.
○ loss값이 내려가다가 갑자기 올라가면 과대적합이다.
   (새로운 데이터가 들어왔을 때, 올라가면 과적합): 과적합은 내 학습용 데이터에만 적응해서 새로운 데이터가 들어오면 큰 변화가 생김?!

 

X=data[['studytime','freetime','traveltime','health']]
y=data['G3']
train,test분리
X_train,X_test,y_train, y_test = train_test_split(X,y,test_size=0.2, random_state=918)
데이터 크기 확인
:
test와 train의 크기가 같은지 봐야함.
X_train.shape, y_train.shape, X_test.shape, y_test.shape

1.신경망 구조설계
## 뼈대
model1 = Sequential()
## 입력층
model1.add(InputLayer(input_shape=(4,)))  # 입력특성이 4개임.
## 중간층
model1.add(Dense(units=10))
model1.add(Activation('sigmoid'))
## 출력층
model1.add(Dense(units=1))
2. 학습방법과 평가 방법 설정
model1.compile(loss='mean_squared_error',
               optimizer='SGD',
               metrics=['mse'])
3.학습
h2=model1.fit(X_train,y_train,validation_split=0.2, epochs=20)

 

4.예측 및 평가
model1.evaluate(X_test, y_test)

5. 시각화
plt.figure(figsize=(10,5))
plt.plot(h2.history['loss'], label='train_loss')
plt.plot(h2.history['val_loss'], label='val_loss')
plt.legend()
plt.show()