1、有一些點的集合,進行Least squares polynomial fit.
x = np.array([-1,0,1]) #x坐標
y = np.array([1,0,1])
f1 = np.polyfit(x,y,2) # f1是擬合后的多項式的系數,是一個array,degree從高到低排列
p = np.poly1d(f1) # p是二項式的函數,可以帶入x進行計算
print(p(1))
2、擬合后我們如何評判擬合的准確程度?
使用R2擬合優度指數進行評價。
我們認為,用y的平均去預測y是一個最差情況(實際上可能比這個還差,比如實際值都是1,預測值卻都是10000),任何預測都應該比這個准.
於是R2=1-SSE/SST 也就是預測值和真實值的殘差平方和要小於平均值和真實值的殘差平方和,即SSE<SST。R2一般介於0和1之間,越大擬合效果越好,但如果模型出乎意料的非常差,可能為負。
Best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse).
計算R2值
from sklearn.metrics import r2_score
coefficient_of_determination = r2_score(y_true, p(x))
y_true: array-like
p(x): array-like