728x90
반응형
SMALL
분류 (Classification)
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.optimizers import SGD, Adam
import numpy as np
try:
loaded_data = np.loadtxt('./example.csv', delimiter=',')
x_data = loaded_data[ :, 0:-1]
t_data = loaded_data[ :, [-1]]
print(x_data.shape, t_data.shape)
except Exception as err:
print(str(err))
(759, 8) (759, 1)
Shuffle
print(x_data[:2])
print(t_data[:2])
s = np.arange(len(x_data))
print(s)
np.random.shuffle(s)
print(s)
x_data = x_data[s]
t_data = t_data[s]
print(x_data[:2])
print(t_data[:2])
[[-0.294118 0.487437 0.180328 -0.292929 0. 0.00149028
-0.53117 -0.0333333 ]
[-0.882353 -0.145729 0.0819672 -0.414141 0. -0.207153
-0.766866 -0.666667 ]]
[[0.]
[1.]]
[ 0 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 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
...
[-0.529412 0.547739 0.0163934 -0.373737 -0.328605 -0.0223547
-0.864219 -0.933333 ]]
[[1.]
[1.]]
TEST_SPLIT_RATIO = 0.1
test_nums = int(TEST_SPLIT_RATIO*len(x_data))
print('test_nums = ', test_nums)
x_test = x_data[:test_nums]
t_test = t_data[:test_nums]
x_data = x_data[test_nums:]
t_data = t_data[test_nums:]
print(x_data.shape, t_data.shape)
print(x_test.shape, t_test.shape)
test_nums = 75
(684, 8) (684, 1)
(75, 8) (75, 1)
VAL_SPLIT_RATIO = 0.1
val_nums = int(VAL_SPLIT_RATIO*len(x_data))
print('val_nums = ', val_nums)
x_val = x_data[:val_nums]
t_val = t_data[:val_nums]
x_data = x_data[val_nums:]
t_data = t_data[val_nums:]
print(x_data.shape, t_data.shape)
print(x_val.shape, t_val.shape)
val_nums = 68
(616, 8) (616, 1)
(68, 8) (68, 1)
이항분류 : Sigmoid
# Logistic Regression을 keras으로 생성
model = Sequential()
# 노드 1개인 출력층 생성
model.add(Dense(t_data.shape[1],
input_shape=(x_data.shape[1],),
activation='sigmoid'))
# 학습을 위한 optimizer, 손실함수 loss 정의
model.compile(optimizer=SGD(learning_rate=0.01),
loss='binary_crossentropy',
metrics=['accuracy'])
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 1) 9
=================================================================
Total params: 9
Trainable params: 9
Non-trainable params: 0
_________________________________________________________________
hist = model.fit(x_data, t_data, epochs=500, validation_data=(x_val, t_val), verbose=2)
Epoch 1/500
20/20 - 3s - loss: 0.7003 - accuracy: 0.5909 - val_loss: 0.6842 - val_accuracy: 0.6618 - 3s/epoch - 149ms/step
Epoch 2/500
20/20 - 0s - loss: 0.6942 - accuracy: 0.6071 - val_loss: 0.6767 - val_accuracy: 0.6618 - 100ms/epoch - 5ms/step
Epoch 3/500
20/20 - 0s - loss: 0.6892 - accuracy: 0.6136 - val_loss: 0.6705 - val_accuracy: 0.7059 - 98ms/epoch - 5ms/step
Epoch 4/500
20/20 - 0s - loss: 0.6848 - accuracy: 0.6250 - val_loss: 0.6645 - val_accuracy: 0.7059 - 86ms/epoch - 4ms/step
Epoch 5/500
20/20 - 0s - loss: 0.6807 - accuracy: 0.6364 - val_loss: 0.6598 - val_accuracy: 0.7059 - 85ms/epoch - 4ms/step
Epoch 6/500
20/20 - 0s - loss: 0.6773 - accuracy: 0.6396 - val_loss: 0.6551 - val_accuracy: 0.7059 - 95ms/epoch - 5ms/step
Epoch 7/500
20/20 - 0s - loss: 0.6740 - accuracy: 0.6445 - val_loss: 0.6511 - val_accuracy: 0.6912 - 87ms/epoch - 4ms/step
Epoch 8/500
20/20 - 0s - loss: 0.6711 - accuracy: 0.6380 - val_loss: 0.6473 - val_accuracy: 0.6912 - 101ms/epoch - 5ms/step
Epoch 9/500
20/20 - 0s - loss: 0.6683 - accuracy: 0.6396 - val_loss: 0.6439 - val_accuracy: 0.6912 - 94ms/epoch - 5ms/step
Epoch 10/500
20/20 - 0s - loss: 0.6657 - accuracy: 0.6461 - val_loss: 0.6402 - val_accuracy: 0.6912 - 98ms/epoch - 5ms/step
Epoch 11/500
20/20 - 0s - loss: 0.6630 - accuracy: 0.6477 - val_loss: 0.6373 - val_accuracy: 0.6912 - 90ms/epoch - 4ms/step
Epoch 12/500
20/20 - 0s - loss: 0.6607 - accuracy: 0.6477 - val_loss: 0.6343 - val_accuracy: 0.6912 - 83ms/epoch - 4ms/step
Epoch 13/500
...
Epoch 500/500
20/20 - 0s - loss: 0.4788 - accuracy: 0.7646 - val_loss: 0.4140 - val_accuracy: 0.8235 - 109ms/epoch - 5ms/step
model.evaluate(x_test, t_test)
3/3 [==============================] - 0s 9ms/step - loss: 0.5611 - accuracy: 0.6933
[0.5610601902008057, 0.6933333277702332]
import matplotlib.pyplot as plt
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.grid()
plt.plot(hist.history['loss'], label='train loss')
plt.plot(hist.history['val_loss'], label='validation loss')
plt.legend(loc='best')
plt.show()
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.grid()
plt.plot(hist.history['loss'], label='train loss')
plt.plot(hist.history['val_loss'], label='validation loss')
plt.legend(loc='best')
plt.show()
다중 분류 : one-hot encoding (O)
# one-hot encoding
t_data_one_hot = tf.keras.utils.to_categorical(t_data, num_classes=2)
print(t_data.shape, t_data_one_hot.shape)
(759, 1) (759, 2)
# Logistic Regression을 keras로 생성
# 다중 분류이므로 출력층은 softmax 함수 적용
model = Sequential()
# 다중 분류이므로 노드 2개인 출력층 생성
model.add(Dense(t_data_one_hot.shape[1],
input_shape=(x_data.shape[1],),
activation='softmax'))
# 학습을 위한 optimizer, 손실함수 loss 정의
model.compile(optimizer=SGD(learning_rate=0.01),
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 2) 18
=================================================================
Total params: 18
Trainable params: 18
Non-trainable params: 0
_________________________________________________________________
다중 분류 : one-hot encoding (X)
# Logistic Regression을 keras로 생성
# 다중 분류이므로 출력층은 softmax 하수 적용
model = Sequential()
# 노드 2개인 출력층 생성
model.add(Dense(2, input_shape=(x_data.shape[1],), activation='softmax'))
# 학습을 위한 optimizer, 손실함수 loss 정의
model.compile(optimizer=SGD(learning_rate=0.01),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 2) 18
=================================================================
Total params: 18
Trainable params: 18
Non-trainable params: 0
_________________________________________________________________
728x90
반응형
LIST
'AI-driven Methodology > Artificial Intelligence' 카테고리의 다른 글
[AI] 와인 품질 예측 (0) | 2022.07.24 |
---|---|
[AI] 표준화 (Standardization) (0) | 2022.07.24 |
[AI] 다변수 선형 회귀 (0) | 2022.07.17 |
[AI] Basic Architecture (0) | 2022.07.17 |
[AI] Feed Forward ∙ One Hot Encoding ∙ Softmax (0) | 2022.07.17 |