使用matplotlib实现**函数的数学公式图

代码实现:

import numpy as np
import matplotlib.pyplot as plt

#  正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
# 正常显示负号
plt.rcParams['axes.unicode_minus'] = False 
x = np.linspace(-6, 6, 1000)

# 实现公式
# 将对应**函数的公式实现代码粘贴到这

# 定义窗口
plt.figure("**函数")
# 画线,
plt.plot(x, y, label='**函数')
plt.xticks([-i for i in range(6, 0,-1)]+[i for i in range(7)], ['{}'.format(-i) for i in range(6, 0,-1)]+['{}'.format(i) for i in range(7)])

# 移动轴线到图中央
ax = plt.gca()
ax.spines['right'].set_color("none")
ax.spines['top'].set_color("none")
ax.spines['bottom'].set_position(("data",0))
ax.spines['left'].set_position(("data",0)) 
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# 标注
# 将对应的**函数的标粘贴到这 

# 将标记放入图中
plt.legend()
# 显示图
plt.show()

1. sigmoid

数学表达式:
σ(x)=11+ex \sigma \left( x\right) =\dfrac {1} {1+e^{-x}}

实现代码:

# 实现公式
y = np.divide(1, (1+np.exp(-x1)))
# 标注
plt.text(-6.2, 0.85, r'$\sigma = \dfrac{1}{1+e^{-x}}$')

效果图:

使用matplotlib实现**函数的数学公式图]

2. Tanh

数学表达式:
tanh(x)=2σ(2x)1 \tanh \left( x\right) =2\sigma \left( 2x\right) -1
实现代码:

# 实现公式1:
y = 2*np.divide(1, (1+np.exp(-2*x)))-1
# 实现公式2:
y = np.divide(np.exp(x)-np.exp(-x), np.exp(x)+ np.exp(-x))

# 标注
plt.text(-6.5, 0.75, r'$Tanh(x) = 2sigmoid(2x)-1$')
plt.text(-6.5, 0.55, r'$Tanh(x) = \dfrac{sinhx}{coshx}=\dfrac{e^x-e^{-x}}{e^x+e^{-x}}$')

效果图:

使用matplotlib实现**函数的数学公式图

3. ReLU

数学表达式:
f(x)=max(0,x)={x,(x>0)0,(x<0) f\left( x\right) =\max \left( 0,x\right) =\begin{cases}x&,(x >0) \\ 0 &,(x<0)\end{cases}
实现代码:

# 实现公式:
y = []
for i in x:
    if i < 0:
        y.append(0)
    else:
        y.append(i)

# 标注        
plt.text(-6.2, 5, 'x < 0 时,'+'x = 0')
plt.text(-6.2, 4.5, 'x > 0 时,'+'x = x')

效果图:

使用matplotlib实现**函数的数学公式图

4. Softplus

数学表达式:
f(x)=In(1+ex) f(x)=In(1+e^x)
实现代码:

# 实现公式:
y = np.log10(1.0 + np.exp(x))
# 标注:
plt.text(-6.4, 2.2, 'f(x)=In(1+e^x)', fontsize=15)

效果图:

使用matplotlib实现**函数的数学公式图

5. ELU

数学表达式:
f(x)={x,x&gt;0a(ex1),x0 f(x)=\begin{cases} x &amp;,x&gt;0\\a(e^x-1)&amp;,x \le0 \end{cases}
实现代码:

# 实现公式
y = []
for i in x:
    if i <= 0:
        y.append(0.25*(np.exp(i)-1))
    else:
        y.append(i)
# 标注
plt.text(-6.2, 5, 'x > 0 时,x = x')
plt.text(-6.2, 4.5, r'x < 0 时, $x = a(e^x-1)+1$ ' )
plt.text(-6.2, 4, 'a 参数可调,此图为0.25')

效果图:

使用matplotlib实现**函数的数学公式图

6. LeakyReLU

数学表达式:
f(x)=max(x,ax)={x,x&gt;0λx,otherwise f(x)=max(x,ax)= \begin{cases} x&amp;,x&gt;0 \\ \lambda x &amp;,otherwise\end{cases}

实现代码:

# 实现LeakyReLU公式
y = []
for i in x:
    if i < 0:
        y.append(i*0.01)
    else:
        y.append(i)

# 标注  
plt.text(-6.2, 5, 'x < 0 时,'+r'$\lambda$'+'=0.01')
plt.text(-6.2, 4.5, 'x > 0 时,'+'x = x')

效果图:

使用matplotlib实现**函数的数学公式图