1. 程式人生 > >使用matplotlib實現啟用函式的數學公式圖

使用matplotlib實現啟用函式的數學公式圖

程式碼實現:

import numpy as np
import matplotlib.pyplot as plt

#  正常顯示中文標籤
plt.rcParams['font.sans-serif'] = ['SimHei']

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}}

實現程式碼:

# 實現公式
number = np.divide(1, (1+np.exp(-number1)))
# 標註
plt.text(-6.2, 0.85, r'$f(x) = \dfrac{1}{1+e^{-x}}$')

效果圖:

Sigmoid.png

2. Tanh

數學表示式: tanh(x)=2σ(2x)1 \tanh \left( x\right) =2\sigma \left( 2x\right) -1 實現程式碼:

# 實現公式1:
number = 2*np.divide(1, (1+np.exp(-2*number1)))-1
# 實現公式2:
number = np.divide(np.exp(number1)-np.exp(-number1), np.exp(number1)+ np.exp(-number1))

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

效果圖:

Tanh.png

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} 實現程式碼:

# 實現公式:
number = []
for i in number1:
    if i < 0:
        number.append(0)
    else:
        number.append(i)

# 標註        
plt.text(-6.2, 5, 'x < 0 時,'+'x = 0')
plt.text(-6.2, 4.5, 'x > 0 時,'+'x = x')

效果圖:

ReLu.png

4. Softplus

數學表示式: f(x)=In(1+ex) f(x)=In(1+e^x) 實現程式碼:

# 實現公式:
number = np.log10(1.0 + np.exp(number1))
# 標註:
plt.text(-6.4, 2.2, 'f(x)=In(1+e^x)', fontsize=15)

效果圖:

Softplus.png

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} 實現程式碼:

# 實現公式
number = []
for i in number1:
    if i <= 0:
        number.append(0.25*(np.exp(i)-1))
    else:
        number.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')

效果圖:

ELU.png

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公式
number = []
for i in number1:
    if i < 0:
        number.append(i*0.01)
    else:
        number.append(i)

# 標註  
plt.text(-6.2, 5, 'x < 0 時,'+r'$\lambda$'+'=0.01')
plt.text(-6.2, 4.5, 'x > 0 時,'+'x = x')

效果圖:

LeakyReLu.png