python - 带有sklearn的numpy多项式线性回归
问题描述
我正在尝试将多项式的线性系统拟合到数据中。numpy
的polynomial
模块包含拟合功能,完美运行。当我尝试使用sklearn
线性求解器拟合模型时,拟合非常糟糕!我不明白出了什么问题。我构造了一个矩阵 X,其中 x_{ij} 对应于第i
th 观察输入和第j
th 多项式。我知道 X 矩阵没问题,因为当我找到带有 的系数时numpy
,数据非常适合。我使用 sklearn 的fit
函数(我尝试了几个线性求解器),但它为(coef_
对象)求解的系数是错误的。我究竟做错了什么?如何使sklearn
线性求解器找到的系数与找到的系数相匹配numpy
?
import numpy as np
from sklearn import linear_model
from sklearn.linear_model import OrthogonalMatchingPursuit
import matplotlib.pyplot as plt
# accept x and polynomial order, return basis of that order
def legs(x, c):
s = np.zeros(c + 1)
s[-1] = 1
return np.polynomial.legendre.legval(x, s)
# Generate normalized samples
samples = np.random.uniform(2, 3, 5)
evals = samples ** 2
xnorm = (samples - 2) * 2 / (3 - 2) - 1
# instantiate linear regressor
omp = linear_model.LinearRegression()
#omp = linear_model.Lasso(alpha=0.000001)
#omp = OrthogonalMatchingPursuit(n_nonzero_coefs=2)
# construct X matrix. Each row is an observed value.
# Each column is a different polynomial.
X = np.array([[legs(xnorm[jj], ii) for ii in range(5)] for jj in range(xnorm.size)])
# Perform the fit. Why isn't this working?
omp.fit(X, evals)
# Plot the truth data
plt.scatter(xnorm, evals, label='data', s=15, marker='x')
# Dot the coefficients found with sklearn against X
plt.scatter(xnorm, omp.coef_.dot(X.T), label='linear regression')
# Dot the coefficients found with numpy against X
plt.scatter(xnorm, np.polynomial.legendre.legfit(xnorm, evals, 4).dot(X.T), label='Numpy regression')
# complete the plot
plt.legend(ncol=3, prop={'size':3})
plt.savefig('simpleExample')
plt.clf()
解决方案
你的omp.coef_.dot(X.T)
不包括拦截;手动添加或直接使用omp.predict
。
IE:
plt.scatter(xnorm, omp.coef_.dot(X.T) + omp.intercept_, label='linear regression')
plt.scatter(xnorm, evals, label='data', s=15, marker='x')
或者
plt.scatter(xnorm, omp.predict(X), label='linear regression')
plt.scatter(xnorm, evals, label='data', s=15, marker='x')
推荐阅读
- javascript - 在一个无法访问。有没有一种简单的方法可以使其可访问(JS)或者我必须放弃它?
- node.js - 无法读取 calendar.events.list 中未定义的属性“数据”
- python - Flask Python mkdirs 在已安装的驱动器上返回“权限被拒绝”
- python - 来自多个列表的父子结构
- typescript - 节点应用程序中的 TypeScript 类型安全
- c# - 将 C# 表达式树编译为方法时,是否可以访问“this”?
- c# - 当 VS Code 中存在多个解决方案文件时,dotnet restore 不创建 bin
- kibana - 如何在 Kibana 中隐藏菜单项
- r - 正则表达式/R 从具有版本号的路径中提取字符串
- javascript - 如何使用 react 将正确的日期格式正确呈现到表格中?