感知器模型詳解

# coding:utf8
import numpy as np
import matplotlib.pyplot as plt

n = 0  # 迭代次數
lr = 0.10  # 學習速率
# 輸入數據
X = np.array([[1, 1, 2, 3],
              [1, 1, 4, 5],
              [1, 1, 1, 1],
              [1, 1, 5, 3],
              [1, 1, 0, 1]])
print(X)
# 標籤
Y = np.array([1, 1, -1, 1, -1])
# 權重初始化,取值範圍-1到1
W = (np.random.random(X.shape[1]) - 0.5) * 2


def get_show():
    # 正樣本
    all_x = X[:, 2]
    all_y = X[:, 3]
    print (all_x )
    print(all_x.shape)
    print (all_y )

    # 負樣本
    all_negative_x = [1, 0]
    all_negative_y = [1, 1]
    print(all_negative_x)
    print(Y.shape)
    print(all_negative_y)

    # 計算分界線斜率與截距
    k = -W[2] / W[3]
    b = -(W[0] + W[1]) / W[3]
    # 生成x刻度
    xdata = np.linspace(0, 5)
    plt.figure()
    plt.plot(xdata, xdata * k + b, 'y')
    plt.plot(all_x, all_y, 'bo')# 用藍色,且點的標記用小圓,'o'  circle marker
    plt.plot(all_negative_x, all_negative_y, 'yo')
    plt.show()


# 更新權值函數
def get_update():
    # 定義所有全局變量
    global X, Y, W, lr, n
    n += 1
    # 計算符號函數輸出
    new_output = np.sign(np.dot(X, W.T))
    # 更新權重
    new_W = W + lr * ((Y - new_output.T).dot(X)) / int(X.shape[0])
    W = new_W


def main():
    for _ in range(100):
        get_update()
        new_output = np.sign(np.dot(X, W.T))
        if (new_output == Y.T).all():
            print("迭代次數:", n)
            break
    get_show()


if __name__ == "__main__":
    main()


運行結果:

 

知識補充:

import numpy as np
x = np.array([[1,2,5],[2,3,5],[3,4,5],[2,3,6]])
#輸出數組的行和列數
print x.shape  #結果: (4, 3)
#只輸出行數
print x.shape[0] #結果: 4
#只輸出列數
print x.shape[1] #結果: 3

需要重點注意的是列表list是沒有shape屬性的,需要將其轉換爲數組,如下可以有兩種表示方式

b = [[1,2,3],[4,5,6],[7,8,9]]
print(np.shape(b))
print(np.array(b).shape)

如果直接用列表的shape屬性,會報如下錯誤

a = [[1,2,3],[4,5,6]]
print(a.shape)

AttributeError: ‘list’ object has no attribute ‘shape’

matplotlib庫的常用知識:
https://www.cnblogs.com/yinheyi/p/6056314.html

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