1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/Python_Ai_Road-eat_tensorflow2_in_30_days

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
Chapter2-3.md 6.2 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 03.12.2024 15:14 374a95e

2-3 Автоматическая дифференциация

Нейронные сети используют обратное распространение для вычисления градиентов и обновления параметров в сети. Вычисление градиента — сложная задача, в которой легко допустить ошибки.

Фреймворк глубокого обучения помогает нам автоматически вычислять градиенты.

tf.GradientTape обычно используется для записи прямого расчёта в Tensorflow, а затем «перематывает» эту «ленту» в обратном направлении для получения градиента.

Это автоматическая дифференциация в TensorFlow.

1. Вычисление производной с помощью Gradient Tape

import tensorflow as tf
import numpy as np

# Вычисление производной функции f(x) = a*x**2 + b*x + c

x = tf.Variable(0.0, name="x", dtype=tf.float32)
a = tf.constant(1.0)
b = tf.constant(-2.0)
c = tf.constant(1.0)

with tf.GradientTape() as tape:
    y = a * tf.pow(x, 2) + b * x + c
    
dy_dx = tape.gradient(y, x)
print(dy_dx)
tf.Tensor(-2.0, shape=(), dtype=float32)
# Использование watch для вычисления производных константного тензора

with tf.GradientTape() as tape:
    tape.watch([a, b, c])
    y = a * tf.pow(x, 2) + b * x + c
    
dy_dx, dy_da, dy_db, dy_dc = tape.gradient(y, [x, a, b, c])
print(dy_da)
print(dy_dc)
tf.Tensor(0.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
# Вычисление второй производной
with tf.GradientTape() as tape2:
    with tf.GradientTape() as tape1:   
        y = a * tf.pow(x, 2) + b * x + c
    dy_dx = tape1.gradient(y, x)   
dy2_dx2 = tape2.gradient(dy_dx, x)

print(dy2_dx2)
tf.Tensor(2.0, shape=(), dtype=float32)
# Используйте это в автографе

@tf.function
def f(x):   
    a = tf.constant(1.0)
    b = tf.constant(-2.0)
    c = tf.constant(1.0)
    
    # Преобразование типа переменной в tf.float32
    x = tf.cast(x, tf.float32)
    with tf.GradientTape() as tape:
        tape.watch(x)
        y = a * tf.pow(x, 2)+b * x+c
    dy_dx = tape.gradient(y, x) 
    
    return((dy_dx, y))

tf.print(f(tf.constant(0.0)))
tf.print(f(tf.constant(1.0)))
(-2, 1)
(0, 0)

2. Вычисление минимального значения через Gradient Tape и оптимизатор

# Вычислить минимальное значение функции f(x) = a*x**2 + b*x + c
# Использовать optimizer.apply_gradients

x = tf.Variable(0.0,name = "x",dtype = tf.float32)
a = tf.constant(1.0)
b = tf.constant(-2.0)
c = tf.constant(1.0)

optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
for _ in range(1000):
    with tf.GradientTape() as tape:
        y = a * tf.pow(x, 2) + b * x + c
    dy_dx = tape.gradient(y,x)
    optimizer.apply_gradients(grads_and_vars=[(dy_dx,x)])
    
tf.print("y =", y, "; x =", x)
y = 0 ; x = 0.999998569
# Рассчитать минимальное значение функции f(x) = a*x**2 + b*x + c
# Использовать optimizer.minimize
# Этот optimizer.minimize идентичен вычислению градиента с помощью ленты, затем вызову apply_gradient

x = tf.Variable(0.0,name = "x",dtype = tf.float32)

# Обратите внимание, что у функции f() нет аргумента
def f():   
    a = tf.constant(1.0)
    b = tf.constant(-2.0)
    c = tf.constant(1.0)
    y = a * tf.pow(x,2)+b * x+c
    return(y)

optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)   
for _ in range(1000):
    optimizer.minimize(f, [x])   
    
tf.print("y =", f(), "; x =", x)
y = 0 ; x = 0.999998569
# Рассчитайте минимальное значение в Autograph
# Используйте optimizer.apply_gradients

x = tf.Variable(0.0,name = "x",dtype = tf.float32)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

@tf.function
def minimizef():
    a = tf.constant(1.0)
    b = tf.constant(-2.0)
    c = tf.constant(1.0)
    
    for _ in tf.range(1000): # Обратите внимание, что мы должны использовать tf.range(1000) вместо range(1000), когда используем Autograph
        with tf.GradientTape() as tape:
            y = a * tf.pow(x, 2) + b * x + c
        dy_dx = tape.gradient(y, x)
        optimizer.apply_gradients(grads_and_vars=[(dy_dx, x)])
        
    y = a * tf.pow(x, 2) + b * x + c
    return y

tf.print(minimizef())
tf.print(x)
0
0.999998569
# Рассчитайте минимальное значение в Autograph
# Используйте
``` ```
optimizer.minimize

x = tf.Variable(0.0, name="x", dtype=tf.float32)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

@tf.function
def f():
    a = tf.constant(1.0)
    b = tf.constant(-2.0)
    c = tf.constant(1.0)
    y = a * tf.pow(x, 2) + b * x + c
    return y

@tf.function
def train(epoch):
    for _ in tf.range(epoch):
        optimizer.minimize(f, [x])
    return f()


tf.print(train(1000))
tf.print(x)
0
0.999998569

Пожалуйста, оставляйте комментарии в официальном аккаунте WeChat «Python与算法之美» (Elegance of Python and Algorithms), если хотите пообщаться с автором о содержании. Автор постарается ответить, учитывая ограниченное время.

Вы также можете присоединиться к групповому чату с другими читателями, ответив 加群 (join group) в официальном аккаунте WeChat.

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/Python_Ai_Road-eat_tensorflow2_in_30_days.git
git@api.gitlife.ru:oschina-mirror/Python_Ai_Road-eat_tensorflow2_in_30_days.git
oschina-mirror
Python_Ai_Road-eat_tensorflow2_in_30_days
Python_Ai_Road-eat_tensorflow2_in_30_days
master