python3__機器學習__神經網路基礎演算法__最小二乘法(LS演算法)
阿新 • • 發佈:2019-01-14
1.LS演算法說明
LS演算法是一種數學優化技術,也是一種機器學習常用演算法。他通過最小化誤差的平方和尋找資料的最佳函式匹配。利用最小二乘法可以簡便的求得未知的資料(1),並使得這些求得的資料與實際資料之間誤差的平方和最小。除此之外最小二乘法還可用於曲線擬合(2),其他一些優化問題(3)也可通過最小化鞥能量或最大化熵用最小二乘法表示。
2.LS演算法原理
最小二乘法實際上解決的是當Ax=C無解的情況下的最優解。
import numpy as np import matplotlib.pyplot as plt # 兩個點A和C A = np.array([[3], [1]]) C = np.array([[1], [3]]) # np.linalg.inv: 計算矩陣的逆 # np.linalg: 提供線性代數工具的模組 # x' = (A.T*A)^(-1)*A.T*C AA = np.linalg.inv(A.T.dot(A)) B = A.T.dot(C) l = AA.dot(B) # P=Ax' P = A.dot(l) x = np.linspace(-2, 2, 10) x.shape = (1, 10) # 畫出直線y=ax # A:(2, 1) # x:(1, 9) # xx:(2, 9) xx = A.dot(x) fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot(xx[0, :], xx[1, :]) # 畫出A點 ax.plot(A[0], A[1], "ko") # 畫出C點和P點的連線 ax.plot([C[0], P[0]], [C[1], P[1]], "r-o") # 畫出OC曲線 ax.plot([0, C[0]], [0, C[1]], "m-o") # 畫出座標軸 ax.axvline(x=0, color="b") ax.axhline(y=0, color="b") # 標寫每個點的字母 # margin: 偏移量 # ax.text: 在座標軸上新增文字 margin = 0.1 ax.text(A[0]+margin, A[1]+margin, r"A", fontsize=20) ax.text(C[0]+margin, C[1]+margin, r"C", fontsize=20) ax.text(P[0]+margin, P[1]+margin, r"P", fontsize=20) ax.text(0+margin, 0+margin, r"o", fontsize=20) ax.text(0+margin, 4+margin, r"y", fontsize=20) ax.text(4+margin, 0+margin, r"x", fontsize=20) plt.xticks(np.arange(-2, 3)) plt.yticks(np.arange(-2, 3)) ax.axis("equal") plt.show()