tensorflow.Keras 를 이용한 딥러닝
Linear Regression (선형 회귀)
# import
import tensorflow as tf
from tensorflow import keras
import numpy as np
# 와 y 데이터 생성
x = np.array(range(20))
y = x * 2 - 1
# x와 y의 shape을 확인해서 노드 정하기
x.shape, y.shape
# 1번 청소
keras.backend.clear_session()
# 2번 모델 발판 선언
model = keras.models.Sequential()
# 3번 모델 레이어 쌓기
model.add( keras.layers.Input(shape=(1,)) )
model.add( keras.layers.Dense(1) )
# 4번 컴파일
model.compile(loss='mse',
optimizer='adam')
#모델 훈련
model.fit(x, y, epochs=10, verbose=1)
#모델 예측값 보기
model.predict(x).reshape(-1)
Logistic Regression (2진 분류문제)
# import 선언
import tensorflow as tf
from tensorflow import keras
import numpy as np
# 학습시킬 x와y 생성
x = np.array(range(20))
y = np.array([0]*10 + [1]*10)
# 청소
keras.backend.clear_session()
# 발판생성
model = keras.models.Sequential()
# 발판위에 레이어 생성
model.add( keras.layers.Input(shape=(1,)) )
model.add( keras.layers.Dense(1, activation='sigmoid') )
# 컴파일(평가)
model.compile(loss='binary_crossentropy',
metrics=['accuracy'],
optimizer='adam')
# 학습!
model.fit(x, y, epochs=10, verbose=1)
# 결과 출력
print(y)
print(model.predict(x))
선형회귀와 차이점으로
Dense(1, activation='sigmoid')
model.compile(loss='binart_crossentropy', metrics=['accuracy'])
를 추가한다.
멀티클래스 분류(3진이상 분류)
# iris 데이터 가져오기
from sklearn.datasets import load_iris
iris = load_iris()
# x와 y설정
x = iris.data
y = iris.target
x.shape, y.shape
x.shape, y.shape = ((150,4), (150,))
One-Hot-Encoding
# keras의 ont-hot-encoding 불러오기
from tensorflow.keras.utils import to_categorical
# one-hot-encoding
y = to_categorical(y, 3)
# shape 확인
x.shape, y.shape
x.shape, y.shape = ((150,4), (150,3))
모델링!
# import
from tensorflow import keras
import tensorflow as tf
import numpy as np
# 청소
keras.backend.clear_session()
# 모델 생성
model = keras.models.Sequential()
#모델 조립
model.add(keras.layers.Input(shape=(4,)))
model.add(keras.layers.Dense(3,activation='softmax'))
# 컴파일
model.compile(loss='categorical_crossentropy',
metrics='accuracy',
optimizer='adam')
# 양념
model.summary()
학습!
model.fit(x,y, epochs=10, verbose=1)
2진 분류 코드에서
from tensorflow.keras.utils import to_categorical
one-hot-encoding후
Dense(3,activation='softmax')
loss='categorical_crossentropy'
를 추가한다.