Python 绘制relu函数及其倒数 带坐标轴

from matplotlib import pyplot as plt
import numpy as np

定义relu函数及其倒数

# ---------------------------------------------

def relu(x):
    """relu函数"""
    return np.where(x<0,0,x)

def dx_relu(x):
    """relu函数的导数"""
    return np.where(x < 0, 0, 1)
# ---------------------------------------------

绘制relu函数relu(x)

# ---------------------------------------------

if __name__ == '__main__':
    x = np.arange(-10, 10, 0.01)
    fx = relu(x)
    dx_fx = dx_relu(x)
    # ---------------------------------------------
    ax = plt.gca()  # 得到图像的Axes对象
    ax.spines['right'].set_color('none')  # 将图像右边的轴设为透明
    ax.spines['top'].set_color('none')  # 将图像上面的轴设为透明
    ax.xaxis.set_ticks_position('bottom')  # 将x轴刻度设在下面的坐标轴上
    ax.yaxis.set_ticks_position('left')  # 将y轴刻度设在左边的坐标轴上
    ax.spines['bottom'].set_position(('data', 0))  # 将两个坐标轴的位置设在数据点原点
    ax.spines['left'].set_position(('data', 0))
    plt.title('relu Function')
    plt.xlabel('x')
    plt.ylabel('fx')
    plt.plot(x, fx)
    plt.show()
    # ---------------------------------------------

绘制rulu函数的导数dx_relu(x)

# ---------------------------------------------
    ax = plt.gca()  # 得到图像的Axes对象
    ax.spines['right'].set_color('none')  # 将图像右边的轴设为透明
    ax.spines['top'].set_color('none')  # 将图像上面的轴设为透明
    ax.xaxis.set_ticks_position('bottom')  # 将x轴刻度设在下面的坐标轴上
    ax.yaxis.set_ticks_position('left')  # 将y轴刻度设在左边的坐标轴上
    ax.spines['bottom'].set_position(('data', 0))  # 将两个坐标轴的位置设在数据点原点
    ax.spines['left'].set_position(('data', 0))
    plt.title('Derivative of relu Function')
    plt.xlabel('x')
    plt.ylabel('dx_fx')
    plt.plot(x, dx_fx)
    plt.show()
    # ---------------------------------------------

就可以得到啦
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值