Skip to content

Instantly share code, notes, and snippets.

@rickiepark
Last active July 4, 2021 13:55
Show Gist options
  • Save rickiepark/e3e1ad9fe0a915d0a143fff17fbb1b09 to your computer and use it in GitHub Desktop.
Save rickiepark/e3e1ad9fe0a915d0a143fff17fbb1b09 to your computer and use it in GitHub Desktop.
compare tf2's raw API vs Keras
# 신경망 모델을 만듭니다.
model = tf.keras.models.Sequential()
# 완전 연결 층을 추가합니다.
model.add(tf.keras.layers.Dense(1))
# 옵티마이저와 손실 함수를 지정합니다.
model.compile(optimizer='sgd', loss='mse')
# 훈련 데이터를 사용하여 에포크 횟수만큼 훈련합니다.
model.fit(X_train.astype(np.float64), y_train, epochs=10)
# 훈련할 가중치 변수를 선언합니다.
w = tf.Variable(tf.zeros(shape=(1)))
b = tf.Variable(tf.zeros(shape=(1)))
## 경사 하강법 옵티마이저를 설정합니다.
optimizer = tf.optimizers.SGD(lr = 0.01)
# 에포크 횟수만큼 훈련합니다.
num_epochs = 10
for step in range(num_epochs):
## 자동 미분을 위해 연산 과정을 기록합니다.
with tf.GradientTape() as tape:
z_net = w * X_train + b
z_net = tf.reshape(z_net, [-1])
sqr_errors = tf.square(y_train - z_net)
mean_cost = tf.reduce_mean(sqr_errors)
## 비용 함수에 대한 가중치의 그래디언트를 계산합니다.
grads = tape.gradient(mean_cost, [w, b])
## 옵티마이저에 그래디언트를 반영합니다.
optimizer.apply_gradients(zip(grads, [w, b]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment