1. 程式人生 > >推理和實現sigmoid啟用函式

推理和實現sigmoid啟用函式

sigmoid啟用函式定義為:

                                                                         f(x) = \frac{1}{1+e^{-x}}

該值域為:(0,1)

求該函式的導數推理過程:

主要是依據複合函式:f(g(x))'= f(u)^{'}g(x)^{'}         

求解過程:

                                                             f(x)^{'} = (\frac{1}{1+e^{-x}})^{'} \\\\= f(g(x))' \\\\=f(u)'g(x)' \\\\=((1+e^{-x})^{-1})^{'}(1+e^{-x})^{'} \\\\= (-1) (1+ e^{-x})^{-1-1} (1+e^{-x})^{'}

先對右邊 (1+e^{-x})^{'} 求導:

                                                             (1+e^{-x})^{'} \\\\= (e^{x(-1)})^{'} \\\\= (-1) e^{x(-1-1)} (e^{x})' \\\\= -e^{-2x} e^{x} \\\\= -e^{-x}

再返回來求解:

                                                              (-1) (1+ e^{-x})^{-1-1} (1+e^{-x})^{'}\\ \\=(-1) (1+ e^{-x})^{-2}* (-e^{-x})\\ \\ = \frac{{}e^{-x}}{(1+e^{-x})^2}\\\\= \frac{1}{1+e^{-x}}(\frac{e^{-x}}{1+e^{-x}})\\\\=\frac{1}{1+e^{-x}}(1-\frac{1}{1+e^{-x}})

又因為

                                                                 f(x) = \frac{1}{1+e^{-x}}

所以最後導數形式為:

                                                                 f(x)^{'} = f(x) (1-f(x))

一般作用:

  1. 取值範圍在0~1之間。 
  2. 對於一個事件發生情況,50%是其結果的分水嶺,選擇函式應該在0.5中心對稱。

可以對這兩個函式畫出影象:                                     

程式碼實現:

import math
import matplotlib.pyplot as plt
import numpy as np

# 以類實現
class Sigmoid:
    def __init__(self, w):
        self.weight_input = w
        self.output = 0.0
    # 原函式
    def obj(self):
        self.output = 1.0 / (1.0 + np.exp(- self.weight_input))
        return self.output
    # 導數
    def der(self):
        if self.output == 0.0:
            self.output = 1.0 / (1.0 + np.exp(- self.weight_input))
        return self.output * (1 - self.output)

# 返回間隔均勻的100個樣本,計算間隔為[start, stop]。
x = np.linspace(-10, 10, 100)
y_obj = Sigmoid(x).obj()
y_der = Sigmoid(x).der()

# 畫圖,原函式
plt.figure(figsize=(12, 12))
plt.subplot(2,2,1)
plt.plot(x, y_obj, color='red', label='primitive function')
plt.ylim((-0.2, 1.2))
plt.legend()
plt.xlabel(r'$f(x) = \frac{1}{1+e^{-x}}$', fontsize=18, color='red')
# 導數
plt.subplot(2,2,2)
plt.plot(x, y_der, color='blue', label='derived function')
plt.ylim((-0.1, 0.5))
plt.legend()
plt.xlabel('f(x)\' = f(x)*(1-f(x))', fontsize=18, color='blue')
plt.show()