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()
# ---------------------------------------------
就可以得到啦