# 1.自动微分以及思考 tf版

## 正式开始

``````import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'
print(tf.__version__)
print(tf.config.list_physical_devices('GPU'))
``````

### 版本之间到底有什么区别

``````with tf.Session(graph = g) as sess:
sess.run(...)
``````

``````import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'

a=tf.constant(2)
b=tf.constant(1)
c=a+b
print(c)
``````

### 函数转为静态计算图

``````@tf.function
return x**2+y**2

print(res)
``````

`decorated()`里面就把我们需要的函数功能留下并且`tf_export`装饰器再装饰一次变成最终静态图模式构建的函数

### 终于开始微分

``````import tensorflow as tf

# 输入一个x
x=tf.Variable(int(input()),dtype=tf.float32)

# 首先设计待微分函数 y=5x^3+3x^2-8x+10
@tf.function
def f():
a=tf.constant(5.0)
b=tf.constant(3.0)
c=tf.constant(-8.0)
tape.watch(x)
y=a*tf.pow(x,3)+b*tf.pow(x,2)+c*x+10
tf.print(dy_dx)
return y

# 打印微分结果
f()
``````

### 微分求最小值

``````import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'

# 输入一个x
x=tf.Variable(int(input()),dtype=tf.float32)

# 首先设计待微分函数 y=5x^3+3x^2-8x+10
@tf.function
def f():
a=tf.constant(5.0)
b=tf.constant(3.0)
c=tf.constant(-8.0)
tape.watch(x)
y=a*tf.pow(x,3)+b*tf.pow(x,2)+c*x+10
tf.print(dy_dx)
return y

# 打印微分结果
f()

# 寻找函数最小值
# global_step = tf.Variable(100)
# lr=tf.compat.v1.train.exponential_decay(0.01,global_step=global_step,decay_rate=0.8,decay_steps=10)
lr=0.01
optimizer=tf.keras.optimizers.SGD(learning_rate=lr)
for _ in range(100):
optimizer.minimize(f,x)
print(f().numpy(),x.numpy())
``````