1. 자동 미분
- 텐서플로우 tape_gradient(): 자동 미분 기능 수행
import tensorflow as tf
w = tf.Variable(2.)
def f(w):
y = w**2
z = 2*y + 5
return z
with tf.GradientTape() as tape:
z = f(w)
gradients = tape.gradient(z, [w])
print(gradients)
2. 자동 미분을 이용한 선형 회귀 구현
w = tf.Variable(4.0)
b = tf.Variable(1.0)
@tf.function
def hypothesis(x):
return w*x + b
x_test = [3.5, 5, 5.5, 6]
print(hypothesis(x_test).numpy())
@tf.function
def mse_loss(y_pred, y):
return tf.reduce_mean(tf.square(y_pred - y))
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [11, 22, 33, 44, 53, 66, 77, 87, 95]
optimizer = tf.optimizers.SGD(0.01)
for i in range(301):
with tf.GradientTape() as tape:
y_pred = hypothesis(x)
cost = mse_loss(y_pred, y)
gradients = tape.gradient(cost, [w, b])
optimizer.apply_gradients(zip(gradients, [w, b]))
if i % 10 == 0:
print("epoch : {:3} | w의 값 : {:5.4f} | b의 값 : {:5.4} | cost : {:5.6f}".format(i, w.numpy(), b.numpy(), cost))
epoch : 0 | w의 값 : 8.2133 | b의 값 : 1.664 | cost : 1402.555542
... 중략 ...
epoch : 280 | w의 값 : 10.6221 | b의 값 : 1.191 | cost : 1.091434
epoch : 290 | w의 값 : 10.6245 | b의 값 : 1.176 | cost : 1.088940
epoch : 300 | w의 값 : 10.6269 | b의 값 : 1.161 | cost : 1.086645
3. 케라스로 구현하는 선형 회귀
- 케라스 모델: Sequential로 model이라는 이름의 모델을 만들고, add를 통해 입력과 출력 벡터의 차원과 같은 필요한 정보들을 추가
model = Sequential()
model.add(keras.layers.Dense(output_dim=1, input_dim=1))
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras import optimizers
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [11, 22, 33, 44, 53, 66, 77, 87, 95]
model = Sequential()
model.add(Dense(1, input_dim=1, activation='linear'))
sgd = optimizers.SGD(lr=0.01)
model.compile(optimizer=sgd, loss='mse', metrics=['mse'])
model.fit(x, y, epochs=300)
print(model.predict([9.5]))