監督學習——感知器算法

目錄

 

分類問題

線性界線

更高維度的界線

感知器

用感知器實現簡單邏輯運算

感知器技巧——計算機如何“學習”分類

感知器算法


分類問題

神經網絡是機器學習中的一個模型,可以用於兩類問題的解答:

  • 分類:把數據劃分成不同的類別

  • 迴歸:建立數據間的連續關係

什麼是分類問題?分類(classification),即找一個函數判斷輸入數據所屬的類別,可以是二類別問題(是/不是),也可以是多類別問題(在多個類別中判斷輸入數據具體屬於哪一個類別)。與迴歸問題(regression)相比,分類問題的輸出不再是連續值,而是離散值,用來指定其屬於哪個類別。分類問題在現實中應用非常廣泛,比如垃圾郵件識別,手寫數字識別,人臉識別,語音識別等。

線性界線

W爲權重,b爲偏差。

更高維度的界線

感知器

多層感知器的結構,稱之爲神經網絡。

用感知器實現簡單邏輯運算

實現AND(與)、OR(或)、NOT(非),XOR(異或)。

感知器技巧——計算機如何“學習”分類

這個分類方法,個人感覺像絕對值誤差方法。整個數據集中的每一個點都會把分類的結果提供給感知器(分類函數),並調整感知器。——這就是計算機在神經網絡算法中,找尋最優感知器的原理。

感知器算法

感知器步驟如下所示。對於座標軸爲 (p,q)(p,q) 的點,標籤 y,以及等式 \hat{y} = step(w_1x_1 + w_2x_2 + b)y^​=step(w1​x1​+w2​x2​+b) 給出的預測

  • 如果點分類正確,則什麼也不做。
  • 如果點分類爲正,但是標籤爲負,則分別減去 \alpha p, \alpha q,αp,αq, 和 \alphaα 至 w_1, w_2,w1​,w2​, 和 bb
  • 如果點分類爲負,但是標籤爲正,則分別將 \alpha p, \alpha q,αp,αq, 和 \alphaα 加到 w_1, w_2,w1​,w2​, 和 bb 上。
import numpy as np
# Setting the random seed, feel free to change it and see different solutions.
np.random.seed(42)

def stepFunction(t):
    if t >= 0:
        return 1
    return 0

def prediction(X, W, b):
    return stepFunction((np.matmul(X,W)+b)[0])

# TODO: Fill in the code below to implement the perceptron trick.
# The function should receive as inputs the data X, the labels y,
# the weights W (as an array), and the bias b,
# update the weights and bias W, b, according to the perceptron algorithm,
# and return W and b.
def perceptronStep(X, y, W, b, learn_rate = 0.01):
    # Fill in code
    for i in range(len(X)):
        y_hat = prediction(X[i], W, b)
        if y[i] - y_hat == 1:   #分類爲負,標籤爲正
            W[0] += X[i][0] * learn_rate
            W[1] += X[i][1] * learn_rate
            b += learn_rate
        if y[i] - y_hat == -1:
            W[0] -= X[i][0] * learn_rate
            W[1] -= X[i][1] * learn_rate
            b -= learn_rate
    return W, b
    
# This function runs the perceptron algorithm repeatedly on the dataset,
# and returns a few of the boundary lines obtained in the iterations,
# for plotting purposes.
# Feel free to play with the learning rate and the num_epochs,
# and see your results plotted below.
def trainPerceptronAlgorithm(X, y, learn_rate = 0.01, num_epochs = 25):
    x_min, x_max = min(X.T[0]), max(X.T[0])
    y_min, y_max = min(X.T[1]), max(X.T[1])
    W = np.array(np.random.rand(2,1))
    b = np.random.rand(1)[0] + x_max
    # These are the solution lines that get plotted below.
    boundary_lines = []
    for i in range(num_epochs):
        # In each epoch, we apply the perceptron step.
        W, b = perceptronStep(X, y, W, b, learn_rate)
        boundary_lines.append((-W[0]/W[1], -b/W[1]))
    return boundary_lines

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章