栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

2、预备知识

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2、预备知识

def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend): 设置matplotlib的轴。 axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_xscale(xscale) axes.set_yscale(yscale) axes.set_xlim(xlim) axes.set_ylim(ylim) if legend: axes.legend(legend) axes.grid()
# 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 True 
2.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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267558.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号