import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
tf.model = tf.keras.Sequential()
tf.model.add(tf.keras.layers.Dense(units=1, input_dim=1))
sgd = tf.keras.optimizers.SGD(lr=0.1)
tf.model.compile(loss='mse', optimizer=sgd)
tf.model.summary()
history = tf.model.fit(x_train, y_train, epochs=100)
y_predict = tf.model.predict(np.array([5, 4]))
print(y_predict)
plt.plot(history.history['loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
Sung Kim님(김성훈 교수님)의 유튜브를 보고 공부한 AI 입니다.
Sung Kim님(김성훈 교수님)의 유튜브 주소 : www.youtube.com/channel/UCML9R2ol-l0Ab9OXoNnr7Lw
Sung Kim
컴퓨터 소프트웨어와 딥러닝, 영어등 다양한 재미있는 이야기들을 나누는 곳입니다.
www.youtube.com
minimize cost의 실습을 통해 그래프의 모양을 알아보겠습니다.
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#배열사용을위한 numpy, 알고리즘 tensorflow, 그래프를위한 matplotlib
모델을 학습후 결과를 위한 input값을 위해 numpy를 import 해줍니다.
그래프를 위해 matplotlib 모듈을 import 해줍니다.
tensorflow는 우리가 사용하는 알고리즘이므로 import 해줍니다.
이때 matplotlib 모듈은 파이썬을 통해 설치 해 주어야합니다.
pip3 install matplotlib
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
#학습을 위한 Dataset
학습을 위해 Dataset을 준비합니다.
tf.model = tf.keras.Sequential()
tf.model.add(tf.keras.layers.Dense(units=1, input_dim=1))
#의도에 맞는 모델을 설정하고 shape 설정
input에 따라 output도 1개이므로 각각 1로 설정하고 이에 맞는 모델인 Sequential을 사용합니다.
sgd = tf.keras.optimizers.SGD(lr=0.1)
tf.model.compile(loss='mse', optimizer=sgd)
#모델에서 목표인 최저 cost를 위해 sgd설정후 모델 컴파일
학습을 진행할 때마다 최저 값인 cost를 찾는것이 목표이므로 경사 하한 알고리즘인 GD를 사용합니다. 이때 0.1 단위로 변경될 수 있게 lr을 0.1로 설정합니다.
tf.model.summary()
#컴파일된 모델 확인
컴파일 후 모델을 확인합니다.
history = tf.model.fit(x_train, y_train, epochs=100)
#dataset을 적용 후 epochs=100을 설정하여 100번 학습
완성된 모델을 학습시키기 위해 미리 준비한 dataset을 지정하고 epochs에 원하는 값을 넣어 원하는 만큼 학습시킵니다. 여기서는 100을 지정했습니다.
y_predict = tf.model.predict(np.array([5, 4]))
print(y_predict)
#모델에 input값을 넣고 그 결과를 확인
학습이 완료되면 input값을 넣어 그 결과를 학인합니다.
plt.plot(history.history['loss']) #그래프 생성
plt.title('Model loss') #그래프 title 지정
plt.ylabel('Loss') # ylabel 지정
plt.xlabel('Epoch') # xlabel 지정
plt.legend(['Train', 'Test'], loc='upper left') #legend를 왼쪽 위에 지정
plt.show()
이렇게 완성된 결과를 한 눈에 알아보기 위해 그래프를 그립니다.
학습이 많이 진행 될 수록 손실도는 최저에 가까워 집니다.
이를 통해 GD를 사용하여 cost를 최저로 만드는 것이 목표이고 반복도가 높아질수록 최저에 더 가까워 지는 것을 알 수 있었습니다.
최종 코드입니다.
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
tf.model = tf.keras.Sequential()
tf.model.add(tf.keras.layers.Dense(units=1, input_dim=1))
sgd = tf.keras.optimizers.SGD(lr=0.1)
tf.model.compile(loss='mse', optimizer=sgd)
tf.model.summary()
history = tf.model.fit(x_train, y_train, epochs=100)
y_predict = tf.model.predict(np.array([5, 4]))
print(y_predict)
plt.plot(history.history['loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
예제 출처 : github.com/hunkim/DeepLearningZeroToAll/blob/master/tf2/tf2-03-1-minimizing_cost_show_graph.py
'학습(구) > AI' 카테고리의 다른 글
Multi-variable linear regression 실습 (0) | 2020.10.04 |
---|---|
Multivariable linear regression (0) | 2020.09.10 |
Linear Regression minimize cost (0) | 2020.09.06 |
Linear Regression 실습 (0) | 2020.09.06 |
Linear Regression (0) | 2020.09.06 |