1. 程式人生 > >Udacity機器學習筆記——深度學習(2)

Udacity機器學習筆記——深度學習(2)

Udacity機器學習筆記——深度學習(2)

感知器

  1. 感知器或者神經元是神經網路的基礎單元,它們對輸入的資料進行判斷,比如說輸入一個學生的學業成績和考試成績,然後感知器根據這兩個值來判斷該學生是否被某大學錄取。那麼,感知器是根據什麼規則來對這兩個值進行比較從而得出結論的呢?感知器更加關注學生的學業成績還是考試成績呢?這裡就需要引入權重的概念。
  2. 分別引入兩個權重,分別於學業成績和考試成績進行相乘,權重越大,那麼說明對應的成績也就更加重要。一開始,這兩個權重是隨機的,那麼感知器訓練通過學習,基於上一次的分類結果的誤差不斷地調整權重,從而獲知什麼樣的成績會被大學所錄取。用數學符號表示就是:
    w
    g r a d e s
    x g r a d e s
    + w t e s t x t e s t w_{grades} \cdot x_{grades} + w_{test} \cdot x_{test}

    如果由m個輸入,相應地得到下面的式子:
    i = 1 m w i x i \sum_{i=1}^{m} w_{i} \cdot x_{i}
  3. 最後,上面的相加式子變成一個輸出結果,通過將該式子作為一個啟用函式的輸入而得到。一個最簡單的啟用函式就是Heaviside step function,階躍函式:
    f ( h ) = { 0 if  h < 0 , 1 if  h 0 . f(h) = \begin{cases} 0& \quad \text {if $h<0$}, \\ 1& \quad \text {if $h \ge 0$}. \end {cases}
    將上面介紹的相加式子帶入該函式,並且引入偏差,可以得到感知器的公式:
    f ( x 1 , x 2 , . . . , x m ) = { 0 if  b + w i x i < 0 , 1 if  b + w i x i 0 . f(x_{1}, x_{2}, ..., x_{m}) = \begin{cases} 0& \quad \text {if $b+\sum w_{i} \cdot x_{i} < 0$}, \\ 1& \quad \text {if $b+\sum w_{i} \cdot x_{i} \ge 0$}. \end {cases}
  4. 根據感知器的公式,我們可以推斷出一組適合AND神經元的權重和偏差。例如,當兩個輸入值都為1時,可以設定 w 1 w_{1} w 2 w_{2} 分別為 1,設定 b b 為-2,那麼僅當兩個輸入值都為1的情況,才可以得到 b + w i x i 0 b+\sum w_{i} \cdot x_{i} \ge 0 的結果,此時式子等於0。
import pandas as pd


weight1 = 1.5
weight2 = 1.0
bias = -2.0

test_inputs = [(0,0), (0,1), (1,0), (1,1)]
correct_outputs = [False, False, False, True]
outputs = []

for test_input, correct_output in zip(test_inputs, correct_outputs):
    linear_combination = weight1*test_input[0] + weight2*test_input[1]+bias
    output = int(linear_combination >= 0)
    is_correct_string = 'Yes' if output == correct_output else 'No'
    outputs.append([test_input[0], test_input[1], linear_combination, output, is_correct_string])

num_wrong = len([output[4] for output in outputs if output[4] == 'No'])
output_frame = pd.DataFrame(outputs, columns=['Input 1', 'Input 2', 'Linear Combination', 'Activation Output', 'Is Correct'])
if not num_wrong:
    print('Nice! You got it all correct. \n')
else:
    print('You got {} wrong. Keep trying! \n'.format(num_wrong))
print(output_frame.to_string(index=False))

通過修改weight1和weight2,以及bias的值,還有correct_outputs的值,可以相應地得到OR和NOT,以及XOR神經元。

梯度下降

  1. 梯度下降是幫助尋找到最小化成本函式的權重和偏重的方法。定義成本函式為:
    C ( w , b ) 1 2 n x y ( x ) a 2 C(w,b) \equiv \frac{1} {2n} \sum_{x} \| y(x)-a \|^{2}
    假設 v = ( w , b ) v=(w,b)
    Δ C C Δ v \Delta C \approx \nabla C \cdot \Delta v
    Δ v = η C \Delta v = - \eta \nabla C
    η \eta 稱之為學習率,是個小的正數。
    從而可以得到:
    v v = v η C v \rightarrow v'= v - \eta \nabla C
    展開可以得到:
    w k w k = w k η C w k w_{k} \rightarrow w'_{k} = w_{k} - \eta \frac {\partial{C}} {\partial w_{k}}
    b l b l = b l η C b l b_{l} \rightarrow b'_{l} = b_{l} - \eta \frac {\partial{C}} {\partial b _{l}}