Big Data展
tensorflow2에서 손실함수 동작 원리 실습해보기
빅브로오
2020. 9. 21. 14:24
tensorflow2에서 손실함수 동작 원리 실습¶
모듈 불러오기
In [1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
가상의 훈련 x, y값 설정
In [2]:
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
모델 keras의 Neural Net, Sequential model load
In [3]:
model = tf.keras.Sequential()
예시로 1개 층, 1개 노드를 갖춘 단순 모델 설계
In [4]:
model.add(tf.keras.layers.Dense(units = 1, input_dim = 1))
In [6]:
opt = tf.keras.optimizers.SGD(lr = 0.1)
model.compile(loss = 'mse', optimizer = opt)
In [7]:
hist = model.fit(x_train, y_train , epochs = 100)
In [8]:
model.summary()
In [12]:
y_pred = model.predict(np.array([5,4]))
print(y_pred)
In [13]:
# plot training & val loss values
plt.plot(hist.history['loss'])
plt.title('Model loss graph')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'])
plt.show()
손실 함수의 그래프 단순한 모델이지만 loss가 낮아지는 방향으로 계속해서 움직인다.