36. Tensorflow

2023. 9. 12. 15:08Google ML Bootcamp/2. Improving Deep Neural Networks

import numpy as np

import tensorflow as tf

 

w = tf.Variable(0, dtype=tf.float32) # tensorflow 변수를 선언해주어야 한다.

optimizer = tf.keras.optimizers.Adam(0.1) # learning_rate = 0.1

 

def train_step():

    with tf.GradientTape() as tape: # 테이프처럼 gradient를 forward과정에서 기록해두면 backward시 다시 되감기로 꺼내올 수 있음

        cost = w**2 + -10*w + 25

    trainable_variables = [w]

    grads = tape.gradient(cost, trainable_variables) # cost를 이용하여 gradient를 계산.

    optimizer.apply_gradients(zip(grads, trainable_variables)) # optimizer를 이용하여 w update 수행. 

print(w)

 

~~~

w = tf.Variable(0, dtype=tf.float32) # tensorflow 변수를 선언해주어야 한다.

x = np.array([1.0, -10.0, 25.0], dtype=np.float32) # 이번에는 cost function에 전달하고자 하는 계수를 변수로 선언

optimizer = tf.keras.optimizers.Adam(0.1) # learning_rate = 0.1

 

def training(x,w, optimizer):

    def cost_fn():

        return x[0]*w**2 + x[1]*w + x[2]

    for i in range(epoch):

        optimizer.minimize(cost_fn, [w]) # 위에서 gradient tape 대신 한줄로 요약 가능하다... 장점.

    return w

 

w = training(x, w, optimizer)

print(w)

 

 

'Google ML Bootcamp > 2. Improving Deep Neural Networks' 카테고리의 다른 글

35. Deep Learning Frameworks  (0) 2023.09.12
34. Training a Softmax Classifier  (0) 2023.09.12
33. Softmax Regression  (0) 2023.09.12
32. Batch Norm at Test time  (0) 2023.09.12
31. Why does Batch Norm Work?  (0) 2023.09.12