# save def plot(X, Y None, xlabel None, ylabel None, legend None, xlim None, ylim None, xscale linear , yscale linear , fmts ( - , m-- , g-. , r: ), figsize (3.5, 2.5), axes None): 绘制数据点。 if legend is None: legend [] set_figsize(figsize) axes axes if axes else d2l.plt.gca() # 如果 X 有一个轴 输出True def has_one_axis(X): return (hasattr(X, ndim ) and X.ndim 1 or isinstance(X, list) and not hasattr(X[0], __len__ )) if has_one_axis(X): X [X] if Y is None: X, Y [[]] * len(X), X elif has_one_axis(Y): Y [Y] if len(X) ! len(Y): X X * len(Y) axes.cla() for x, y, fmt in zip(X, Y, fmts): if len(x): axes.plot(x, y, fmt) else: axes.plot(y, fmt) set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
x np.arange(0, 3, 0.1) plot(x, [f(x), 2 * x - 3], x , f(x) , legend [ f(x) , Tangent line (x 1) ])#tangent line切线 legend应该就是角上的那个注释
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fkGjkwqL-1632574408515)(output_100_0.svg)]
import numpy as np from matplotlib import pyplot as plt
def fun1(x): return x**3-1/x
def numberical_lim(f,x): h 1e-4 return (f(x h)-f(x))/h
def tangent_line(f,x): 求切线 调用numberical d numberical_lim(f,x) y f(x)-d*x return lambda t:d*t y
x np.arange(0.0,20.0,0.1) y fun1(x) plt.xlabel( x ) plt.ylabel( f(x) ) tf tangent_line(fun1,1) y2 tf(x) plt.plot(x,y) plt.plot(x,y2) plt.show()
ipython-input-27-83e068b80091 :2: RuntimeWarning: divide by zero encountered in true_divide return x**3-1/x
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Phr2It4j-1632574408517)(output_105_1.svg)]
2.5自动求导import tensorflow as tf x tf.range(4,dtype tf.float32)
tf.Tensor: shape (4,), dtype float32, numpy array([0., 1., 2., 3.], dtype float32)
在我们计算 y 关于 x 的梯度之前 我们需要一个地方来存储梯度
x tf.Variable(x)
with tf.GradientTape() as t: y 2 * tf.tensordot(x,x,axes 1)#计算y 2x⊤x
tf.Tensor: shape (), dtype float32, numpy 28.0
x_grad t.gradient(y,x) x_grad
tf.Tensor: shape (4,), dtype float32, numpy array([ 0., 4., 8., 12.], dtype float32)
x_grad 4*x
tf.Tensor: shape (4,), dtype bool, numpy array([ True, True, True, True])
with tf.GradientTape() as t: y tf.reduce_sum(x)
tf.Tensor: shape (), dtype float32, numpy 6.0
t.gradient(y,x)
tf.Tensor: shape (4,), dtype float32, numpy array([1., 1., 1., 1.], dtype float32)
with tf.GradientTape() as t: y x*x t.gradient(y,x)#等价于y tf.reduce_sum(x*x) #可以认为这是一个一般求导的方法
tf.Tensor: shape (4,), dtype float32, numpy array([0., 2., 4., 6.], dtype float32)
#设置 persistent True以多次运行t.gradient多次。 原本运行一次 #就会被删除以不占用空间 with tf.GradientTape(persistent True) as t: y x*x u tf.stop_gradient(y)#产生一个新变量u 与y具有相同的值 但 #但丢弃计算图中如何计算y的任何信息。换句话说 梯度不会向后流 #经u到x。因此 下面的反向传播函数计算z u*x关于x的偏导数 同时 #将u作为常数处理 而不是z x*x*x关于x的偏导数。 z u*x x_grad t.gradient(z,x) x_grad u
tf.Tensor: shape (4,), dtype bool, numpy array([ True, True, True, True])
t.gradient(y,x) 2*x
tf.Tensor: shape (4,), dtype bool, numpy array([ True, True, True, True])
t.gradient(u,x) 2*x
False
def f(a): b a*2 while tf.norm(b) 1000:#tf.norm()求范数 b b*2 if tf.reduce_sum(b) 0: else: c 100*b return c
a tf.Variable(tf.random.normal(shape ())) with tf.GradientTape() as t: d f(a) d_grad t.gradient(d, a) d_grad
tf.Tensor: shape (), dtype float32, numpy 409600.0
d_grad d/a
tf.Tensor: shape (), dtype bool, numpy True2.6 概率
%matplotlib inline import numpy as np import tensorflow as tf import tensorflow_probability as tfp from d2l import tensorflow as d2l
--------------------------------------------------------------------------- importError Traceback (most recent call last) ipython-input-28-d5324e917c9e in module 2 import numpy as np 3 import tensorflow as tf ---- 4 import tensorflow_probability as tfp 5 from d2l import tensorflow as d2l



