多项式拟合

import matplotlib.pyplot as plt
import numpy as np

n_dots = 20

x = np.linspace(0,1,n_dots)
# print(x,end=" ")
y = np.sqrt(x) + 0.2*np.random.rand(n_dots) - 0.1
# print(y,end=" ")

# 画出拟合多项式
def plot_polynomial_fit(x,y,order):
    p = np.poly1d(np.polyfit(x,y,order))
    
    t = np.linspace(0,1,200)
    # 原始(x,y)点集蓝色原点;拟合曲线为绿色实线;sqrt(t)线为红色虚线
    plt.plot(x,y,"bo",t,p(t),"g-",t,np.sqrt(t),"r--")
    return p

plt.figure(figsize=(18,4))
title = ["Under Fitting","Fitting","Over Fitting"]
models = [None,None,None]
for index,order in enumerate([1,3,10]):
    plt.subplot(1,3,index+1)
    models[index] = plot_polynomial_fit(x,y,order)
    plt.title(title[index],fontsize = 20)

多项式拟合_第1张图片

for m in models:
    print('model coeffs: {0}'.format(m.coeffs))

model coeffs: [0.82680291 0.24431688]

model coeffs: [ 0.93320419 -2.05695594 2.02965729 0.1010051 ]

model coeffs: [ 1.65263070e+04 -8.37302660e+04 1.81150353e+05 -2.18393617e+05 1.60530132e+05 -7.39240670e+04 2.10659112e+04 -3.51674861e+03 3.00168457e+02 -7.29165386e+00 7.91057774e-02]

你可能感兴趣的:(多项式拟合)