深度学习PyTorch笔记(10):PyTorch绘制函数图像及切线
深度学习PyTorch笔记(10):PyTorch绘制函数图像及切线
这是《动⼿学深度学习》(PyTorch版)(Dive-into-DL-PyTorch)的学习笔记,⾥⾯有⼀些代码是我⾃⼰拓展的。
其他笔记在专栏 中。
学习⾃,当时学的时候没运⾏成功,就是因为d2l的导⼊问题,现在⽤pip install d2l搞好了,所以⼲脆把这⾥⾯的代码拿出来学习⼀遍。不过d2l这个包是他们团队⾃⼰写的。
#pip install d2l  安装d2l这个包,这是重点,要不然后⾯编译不出
%matplotlib inline  #在plot时,默认嵌⼊到notebook⾥⾯
import numpy as np
from IPython import display
from d2l import torch as d2l
def f(x):
return3* x **2-4* x
def numerical_lim(f, x, h):
return(f(x + h)- f(x))/ h
h =0.1
for i in range(5):
print(f'h={h:.5f}, numerical limit={numerical_lim(f,1, h):.5f}')
h *=0.1
h=0.10000, numerical limit=2.30000
h=0.01000, numerical limit=2.03000
h=0.00100, numerical limit=2.00300
svg图形
h=0.00010, numerical limit=2.00030
h=0.00001, numerical limit=2.00003
注意,注释#@save是⼀个特殊的标记,会将对应的函数、类或语句保存在d2l包中 因此,以后⽆须重新定义就可以直接调⽤它们(例
如,d2l.use_svg_display())。
def use_svg_display():#@save
"""使⽤svg格式在Jupyter中显⽰绘图。"""
display.set_matplotlib_formats('svg')
我们定义set_figsize函数来设置图表⼤⼩。注意,这⾥我们直接使⽤d2l.plt,因为导⼊语句from matplotlib import pyplot as plt已在前⾔中标记为保存到d2l包中。
def set_figsize(figsize=(3.5,2.5)):#@save
"""设置matplotlib的图表⼤⼩。"""
use_svg_display()
Params['figure.figsize']= figsize
下⾯的set_axes函数⽤于设置由matplotlib⽣成图表的轴的属性。
#@save
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)
通过这三个⽤于图形配置的函数,我们定义了plot函数来简洁地绘制多条曲线,因为我们需要在整个书中可视化许多曲线。
#@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 a()
# 如果 `X` 有⼀个轴,输出True
def has_one_axis(X):
return(hasattr(X,"ndim")and X.ndim ==1or 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)
u=f(x)x=1y=2x−3
现在我们可以绘制函数  及其在  处的切线 , 其中系数 2 是切线的斜率。
x = np.arange(0,3,0.1)
plot(x,[f(x),2* x -3],'x','f(x)', legend=['f(x)','Tangent line (x=1)'])

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。