【发布时间】:2018-02-16 04:36:18
【问题描述】:
我正在编写一个 python 代码来调查使用 [0,1] 范围内的函数 sin(2.pi.x) 的过度拟合。我首先通过使用 mu=0 和 sigma=1 的高斯分布添加一些随机噪声来生成 N 个数据点。我使用第 M 多项式拟合模型。这是我的代码
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# generate N random points
N=30
X= np.random.rand(N,1)
y= np.sin(np.pi*2*X)+ np.random.randn(N,1)
M=2
poly_features=PolynomialFeatures(degree=M, include_bias=False)
X_poly=poly_features.fit_transform(X) # contain original X and its new features
model=LinearRegression()
model.fit(X_poly,y) # Fit the model
# Plot
X_plot=np.linspace(0,1,100).reshape(-1,1)
X_plot_poly=poly_features.fit_transform(X_plot)
plt.plot(X,y,"b.")
plt.plot(X_plot_poly,model.predict(X_plot_poly),'-r')
plt.show()
Picture of polynomial regression
我不知道为什么我有 M=2 行第 m 多项式行?我认为不管M如何,它都应该是1行。你能帮我解决这个问题吗?
【问题讨论】:
标签: python-3.x matplotlib machine-learning scikit-learn regression