python最小二乘法擬合直線

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
from scipy.interpolate import spline


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.figure(figsize=(16,8),dpi=100)
#設置座標刻度值的大小以及刻度值的字體
plt.tick_params(labelsize=16)

font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 16,
}

def Least_squares(x,y):
    x_ = x.mean()
    y_ = y.mean()
    m = np.zeros(1)
    n = np.zeros(1)
    k = np.zeros(1)
    p = np.zeros(1)
    for i in np.arange(7):
        k = (x[i]-x_)* (y[i]-y_)
        m += k
        p = np.square( x[i]-x_ )
        n = n + p
    a = m/n
    b = y_ - a* x_
    return a,b


# a,b = Least_squares(x,y)
# print(a,b)
# y1 = a * x + b
# plt.figure(figsize=(10, 5), facecolor='w')
# plt.plot(x, y, 'ro', lw=2, markersize=6)
# plt.plot(x, y1, 'r-', lw=2, markersize=6)
# plt.grid(b=True, ls=':')
# plt.xlabel(u'X', fontsize=16)
# plt.ylabel(u'Y', fontsize=16)
# plt.show()



x = np.array([400,600,800,1000,1200,1400,1600]) #圖像分辨率

y4 =np.array([14,35,45,65,84,129,155]) #PCAtimeconsumingnote 35
y6 = np.array([4,7,12,20,26,37,42]) #PCA+2timeconsumingnote


# xnew = np.linspace(x.min(),x.max(),300) #300 represents number of points to make between T.min and T.max
# y4_smooth = spline(x,y4,xnew)
# y6_smooth = spline(x,y6,xnew)

a1,b1 = Least_squares(x,y4)
y4_new = a1 * x + b1

a2,b2 = Least_squares(x,y6)
y6_new = a2 * x + b2

# plt.plot(xnew,y4_smooth,label ='PCA')
# plt.plot(xnew,y6_smooth,label ='Two-layer PCA')
plt.plot(x,y4_new,label ='PCA')
plt.plot(x,y6_new,label ='Two-layer PCA')
plt.xlabel('Image size/ pixel',font1)
plt.ylabel('Time taken for registration/ ms',font1)
plt.grid()  # 生成網格
plt.legend(prop=font1,loc='upper center', bbox_to_anchor=(0.45, 1))
plt.savefig('timeconsuming.jpg')
plt.show()

 

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