이라는 cost function이 존재할때,
cost function의 최솟값을 구한다면 w=5이다.w = tf.Variable(0, dtype=tf.float32) # 가중치 선언 optimizer = tf.keras.optimzers.Adam(0.1) # lr = 0.1 def train_step(): # training step with tf.GradientTape() as tape: # casette tape 처럼 기록을 남긴다. 재방문 가능 cost = w**2 -10 * w + 25 trainable_variables = [w] grads = tape.gradient(cost, trainable_variables) optimizer.apply_gradients(zip(grads, trainable_variables)) # zip으로 묶는다. print(w) # 0 값이다. train_step() # 0.09999.. for i in range(1000): train_step() # 거의 5이다.
w = tf.Variable(0, dtype=tf.float32) # 가중치 선언 x = np.array([1.0,-10.0,25.0], dtype=np.float32) optimizer = tf.keras.optimzers.Adam(0.1) # lr = 0.1 def cost_fn(): cost = x[0] * w ** 2 + x[1] * w +x[2] def training(x, w, optimizer): for i in range(1000): optimizer.minmize(cost_fn, [w]) return w print(w) # 0 값 optimizer.minmize(cost_fn, [w]) print(w) # 0.099999.. w = training(x,w,optimizer) print(w) # 5에 가까운 값