참고: https://youtu.be/A9JqeLvAI3g?si=rydFLAjQyVhhcwPz
영상에서 나온 예제코드는 맨 아래 붙여 놓았다.
이번 예시의 문제는 다음과 같다.
3개의 입력데이터에 대해서 1개의 출력데이터가 있고, 이것에 대한 훈련용 데이터가 있고 테스트 데이터도 주어진다.
훈련후, 테스트 데이터를 통해서 얼마나 잘 추론하였는지 알아보자.
먼저 필요한 패키지들을 import하고 데이터를 입력한다.
이에 적합한 모델을 만들고 확인해보자.
훈련시키고, 확인해보자.
훈련하는 동안 마지막 로그를 보면 loss: 2.9755e-11 이다. '0'이나 다름없다.
테스트 데이터를 넣었을 때 정답과 비교해보면 맞춘거나 다름없다.
이를 학습했을 때 결과값인 hist를 통해서 아래와 같이 확인할 수 있다.
아래는 코드 전문이다.
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
import matplotlib.pyplot as plt
print(tf.__version__)
x_data = np.array([ [1,2,0], [5,4,3], [1,2,-1], [3,1,0], [2,4,2],
[4,1,2], [-1,3,2], [4,3,3], [0,2,6], [2,2,1],
[1,-2,-2], [0,1,3], [1,1,3], [0,1,4], [2,3,3] ])
t_data = np.array([-4, 4, -6, 3, -4,
9, -7, 5, 6, 0,
4, 3, 5, 5, 1])
print('x_data.shape = ', x_data.shape, ', t_data.shape = ', t_data.shape)
model = Sequential()
model.add(Dense(1, input_shape=(3, ), activation='linear'))
model.compile(optimizer=SGD(learning_rate=1e-2), loss='mse')
model.summary()
hist = model.fit(x_data, t_data, epochs=1000)
test_data = [ [5,5,0], [2,3,1], [-1,0,1], [10,5,2], [4,-1,-2]]
ret_val = [2*data[0] - 3*data[1] + 2*data[2] for data in test_data]
prediction_val = model.predict(np.array(test_data))
print(prediction_val)
print(ret_val)
plt.title('Loss Trend')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.grid()
plt.plot(hist.history['loss'], label='train loss')
plt.legend(loc='best')
plt.show()
'AI > TensorFlow 학습' 카테고리의 다른 글
6. TensorFlow 2.x - Deep Learning 소개 (0) | 2024.07.31 |
---|---|
5. TensorFlow 2.x - Logistic Regression 예제 (0) | 2024.07.30 |
4. TensorFlow 2.x - Logistic Regression / Classification 이론 (0) | 2024.07.30 |
2. TensorFlow 2.x - Linear Regression 이론 (0) | 2024.07.29 |
1. TensorFlow 2.x - Eager Execution, Keras 시작 (0) | 2024.07.29 |