《动手学深度学习》学习笔记4

求导数、画图代码

导入包

import matplotlib_inline
# jupyter notebook用法
# %matplotlib inline
import numpy as np
# 安装命令:pip install IPython
from IPython import display
from d2l import torch as d2l
import matplotlib.pyplot as plt

求导数代码

# 导数
# 定义函数
def f(x):
    return 3 * 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
h = 0.00010,numerical limit = 2.00030
h = 0.00001,numerical limit = 2.00003

画图代码

def use_svg_display():
    """使用svg格式显示绘图"""
    # 这是旧版python支持的用法,新版不支持
    # display.set_matplotlib_formats('svg')
    matplotlib_inline.backend_inline.set_matplotlib_formats('svg')


def set_figsize(figsize=(3.5, 2.5)):
    """设置图表大小"""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize


def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
    """设置轴"""
    axes.set_xlabel(xlabel)
    axes.set_ylabel(ylabel)
    # 设置x轴缩放
    axes.set_xscale(xscale)
    axes.set_yscale(yscale)
    axes.set_xlim(xlim)
    axes.set_ylim(ylim)
    # 图例
    if legend:
        axes.legend(legend)
    # 函数用于设置绘图区网格线
    axes.grid()


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):
    """绘制数据点"""
    """
    fmts:
    -:表示黑色线
    m--:表示虚线红色
    g-.:表示绿色实线,”.“表示实线
    r:红色的点线
    """
    # 图标
    if legend is None:
        legend = []
    set_figsize(figsize)
    axes = axes if axes else d2l.plt.gca()

    # 如果X有一个轴,则输出True
    def has_one_axis(X):
        '''
        hasattr(X, "ndim"):判断X是否有ndim属性
        X.ndim==1:判断x的维度是否为1
        isinstance(X,list):判断X是否为列表类型
        hasattr((X[0],"__len__")):判断X是否至少含有一个元素,防止X[0]访问越界报错
        '''
        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,即当前figure中的活动的axes,但其他axes保持不变。
    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)'])
# pycharm运行记得添加这句代码
plt.show()

运行输出的图像

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值