1 回答

TA貢獻1812條經驗 獲得超5個贊
如果你的 x 是一維列向量,np.polyfit()
并且np.polyval()
將完成工作。np.polyfit(x,y,order,full=True)
返回殘差(我相信是殘差平方和)供您檢查最佳順序。您不需要第二次回歸擬合來獲得殘差。
注意,您選擇最小殘差的邏輯在工程師方面是可行的,但在數學上并不合理。這是因為誤差平方和 (SSE) 始終會隨著回歸量數量的增加而減小,因此您始終會從最大多項式階次獲得結果。您必須嘗試使用帶有懲罰的公式,以便在選擇模型時添加更多項(例如AIC或BIC標準)。然而,這部分完全由研究者自由選擇,當然超出了問題本身的范圍。
import numpy as np
import matplotlib.pyplot as plt
# get your x and y as np array
x = np.random.uniform(-1,1, 100)
y = x - x**2 + x**3 - x**4 + np.random.normal(0, 0.1, 100)
def poly_fit(n):
? ls_res=[]
? ls_coeff = []
? for i in range(2, n):
? ? coeff, res, _, _, _ = np.polyfit(x, y, i, full=True)
? ? ls_res.append(res)
? ? ls_coeff.append(coeff)
? # argmin should be taken from a penalized loss function
? # add it here
? return ls_coeff[np.argmin(ls_res)]
plt.scatter(x, y, color='red')
coeff = poly_fit(6)
plt.plot(np.sort(x), np.polyval(coeff, np.sort(x)), color='blue')
plt.title('Polynomial Regression results')
plt.xlabel('Position/level')
plt.ylabel('Salary')
plt.show()
添加回答
舉報