Classification
데이터 조건
- 결측치가 없어야 한다.
- 범주형 변수는 one-hot encoding을 적용해야 한다.
- 예측값은 수치형으로 변환해야 한다.
from random import shuffle
x1 = list(range(0,100))
x2 = list(range(100,200))
y = [0,1] * 50
shuffle(x1)
shuffle(x2)
shuffle(y)
import pandas as pd
df = pd.DataFrame( {'x1':x1, 'x2':x2, 'y':y} )
// df
x1 x2 y
0 39 117 0
1 95 110 1
2 75 183 0
3 8 194 0
4 87 104 1
... ... ... ...
95 99 101 1
96 22 126 1
97 59 146 0
98 29 173 1
99 20 122 0
> 패키지 불러오기
import tensorflow as tf
> 예측값 변환
- 범주 데이터를 n 차원 array로 변환해주어야 한다.
y_t = tf.keras.utils.to_categorical(df.y, num_classes=2)
// y_t
array([[1., 0.],
[0., 1.],
[1., 0.],
[1., 0.],
...
> 모델 구성
- 모델의 layer를 쌓고 분석 함수를 정의해준다.
- input_shape의 첫 번째 인자는 독립 변수의 갯수( X 의 차원 )과 일치해야 한다.
- 마지막 layer의 units 수는 범주의 갯수( n ) 와 동일하여야 한다.
model = tf.keras.Sequential(
[ tf.keras.layers.Dense(units=128, activation='relu', input_shape=(2,)),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=16, activation='relu'),
tf.keras.layers.Dense(units=4, activation='relu'),
tf.keras.layers.Dense(units=2, activation='sigmoid') ])
> 모델 Complie
- 모델의 최적화 함수, loss 함수, metric을 정의해준다.
# Binary Classification
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss='binary_crossentropy',
metrics=['accuracy'])
# Muti Classification
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Model 구성 확인 API
model.summary()
> 모델 적합
- 학습 데이터를 주어 모델을 적합시킨다.
- history 객체엔 epoch 별 계산된 수치값(loss, accuarcy) 들이 담긴다.
history = model.fit(df[['x1','x2']],
y_t,
epochs=100,
batch_size=32,
validation_split=0.25,
callbacks=[tf.keras.callbacks.EarlyStopping(patience=10, monitor='val_loss')])
# Callback 함수 수동 정의
class PrintDot(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
// epoch 별 실행
callbacks = [ PrintDot() ]
> 모델 평가
- 테스트 데이터를 넣어 모델의 정확도를 점검한다.
model.evaluate(X_test, y_test)
> 모델 저장
- 모델의 가중치를 저장한다.
- 추후에 이를 이용해 모델을 불러올 수 있다.
model.save('./model')
> 모델 예측
- 예측 데이터의 예측값을 얻어낸다.
model.predict(df_test)
> 모델 예측 수준 확인
from sklearn import metrics
print(metrics.classification_report(y_test, predict_result, labels=[0,1]))
Regression
데이터 조건
- 결측치가 없어야 한다.
- 범주형 변수는 one-hot encoding을 적용해야 한다.
from random import shuffle
x1 = list(range(0,100))
x2 = list(range(100,200))
y = list(range(0, 100))
shuffle(x1)
shuffle(x2)
shuffle(y)
import pandas as pd
df = pd.DataFrame( {'x1':x1, 'x2':x2, 'y':y} )
// df
x1 x2 y
0 91 141 12
1 98 144 79
2 18 198 44
3 92 116 13
4 77 168 49
... ... ... ...
95 23 165 45
96 49 173 57
97 14 136 76
98 47 172 95
99 37 178 84
> 패키지 불러오기
import tensorflow as tf
> 모델 구성
- 모델의 layer를 쌓고 분석 함수를 정의해준다.
- input_shape의 인자는 독립 변수의 갯수( X 의 차원 )과 일치해야 한다.
- 마지막 layer의 units 수를 1로 잡아야 한다.
model = tf.keras.Sequential(
[ tf.keras.layers.Dense(64, activation='relu', input_shape=[2]),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1) ])
> 모델 Complie
- 모델의 최적화 함수, metric을 정의한다.
optimizer = tf.keras.optimizers.RMSprop(0.001)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae', 'mse'])
# Model 구성 확인 API
model.summary()
> 모델 적합
- 학습 데이터를 주어 모델을 적합시킨다.
- history 객체엔 epoch 별 계산된 수치값(loss, mae, mse) 들이 담긴다.
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
history = model.fit(
df[['x1','x2']], df.y,
epochs=500, validation_split = 0.2, verbose=0,
callbacks=[early_stop])
// pd.DataFrame(history.history)
loss mae mse val_loss val_mae val_mse
0 2517.642334 42.239021 2517.642334 1775.801514 33.830116 1775.801514
1 1692.830811 33.803822 1692.830811 1384.023071 30.523922 1384.023071
2 1295.098389 29.749792 1295.098389 1176.097656 28.595428 1176.097656
3 1079.222290 27.739096 1079.222290 1083.582031 27.601196 1083.582031
4 970.851746 26.342365 970.851746 1044.255127 27.384928 1044.255127
...
> 모델 평가
- 테스트 데이터를 넣어 모델의 예측 수치를 산출한다.
model.evaluate(X_test, y_test)
// loss, mae, mse
> 모델 저장
- 모델의 가중치를 저장한다.
- 추후에 이를 이용해 모델을 불러올 수 있다.
model.save('./model')
> 모델 예측
- 예측 데이터의 예측값을 얻어낸다.
model.predict(df_test)
> 결과 시각화
- 에폭 별 예측 수치 변화
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.figure(figsize=(8,12))
plt.subplot(2,1,1)
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [MPG]')
plt.plot(hist['epoch'], hist['mae'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mae'],
label = 'Val Error')
plt.legend()
plt.subplot(2,1,2)
plt.xlabel('Epoch')
plt.ylabel('Mean Square Error [$MPG^2$]')
plt.plot(hist['epoch'], hist['mse'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mse'],
label = 'Val Error')
plt.legend()
plt.show()
'데이터분석 > python' 카테고리의 다른 글
Pandas API (0) | 2021.08.18 |
---|