1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
 
from tensorflow.keras.datasets import boston_housing
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.optimizers import SGD,  Adam
 
print(tf.__version__)
 
 
# 데이터셋 생성 및 정규화
# 특성별로 상이한 스케일을 가지게 되면 학습이 어려워진다.
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
 
print(x_train.shape, y_train.shape)  # (404, 13) (404,)
print(x_test.shape, y_test.shape)  # (102, 13) (102,)
 
mean = x_train.mean(axis=0)  # 각 특성에 대해 평균을 빼고, 표준편차로 나눈다.
x_train -= mean
std = x_train.std(axis=0)
x_train /= std
 
x_test -= mean
x_test /= std
 
 
# 모델 구축
def make_model():
    model = Sequential()
    model.add(Dense(64, activation='relu', input_shape=(x_train.shape[1],)))  # 선형회귀가 아니다
    model.add(Dense(64, activation='relu'))
    model.add(Dense(1))
    return model
 
 
# 모델 컴파일 (모델을 로드하는 부분에서 수행함)
 
 
# 모델 학습
# 데이터의 수가 많지 않은 경우, 신뢰있는 평가를 할 수 없음 -> k겹 교차검증(k-fold cross-validation)
 
epochs = 300
k_folds = 4
num_val_samples = len(x_train) // k_folds  # 404//4 -> 101, (/-> float, //-> int)
total_mae_histories = []
 
for k_fold in range(k_folds):
 
    val_data = x_train[k_fold*num_val_samples:(k_fold+1)*num_val_samples]
    val_label = y_train[k_fold*num_val_samples:(k_fold+1)*num_val_samples]
 
    crop_x_train = np.concatenate([x_train[:k_fold*num_val_samples], x_train[(k_fold+1)*num_val_samples:]], axis=0)
    crop_y_train = np.concatenate([y_train[:k_fold * num_val_samples], y_train[(k_fold + 1* num_val_samples:]],axis=0)
 
    model = make_model()
    model.compile(optimizer='rmsprop', loss='mse', metrics='mae')  #mse:평균제곱오차, mae:평균절대오차
    # 분류에서는 평가지표로 정확도를 주로 사용하지만, 회귀에서는 일반적으로 mae를 쓴다.
 
    history = model.fit(crop_x_train, crop_y_train, validation_data=(val_data, val_label),
                        epochs=epochs, batch_size=32, verbose=0)
    total_mae_histories.append(history.history['val_mae'])
 
 
# total_mae_histories => (4, 300), ave_mae_history =>(300,)
ave_mae_history = [np.mean([x[i] for x in total_mae_histories]) for i in range(epochs)]
 
# 모델 평가 및 예측
 
 
 
# 모델 저장 및 로드
# model.save("model_name.h5")
# model = tf.keras.models.load_model("model_name.h5")
 
 
# 모델 손실함수 추이확인
plt.plot(range(1len(ave_mae_history)+1), ave_mae_history)
plt.xlabel("epoch")
plt.ylabel("mae")
plt.show()
 
cs

 

위 소스코드를 실행시키면 아래와 같은 출력값을 얻을 수 있다.

 

반응형

'머신러닝_딥러닝 > Tensorflow + Keras' 카테고리의 다른 글

(Tensorflow 2.x) Logistic Regression 2탄  (0) 2021.10.23
(Tensorflow 2.x) Logistic Regression 1탄  (0) 2021.10.23
(Tensorflow 2.x) Regression 1탄  (0) 2021.10.23
MNIST 2탄 (Back Propagation)  (0) 2021.10.23
MNIST 1탄  (0) 2021.10.23

+ Recent posts