gpt4 book ai didi

Python PolynomialFeatures 将数据转换为与原始数据不同的形状

转载 作者:行者123 更新时间:2023-11-30 09:51:24 24 4
gpt4 key购买 nike

我正在使用 sklearn 的 PolynomialFeatures 将数据预处理为各种程度的变换,以便比较它们的模型拟合度。下面是我的代码:

    from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
np.random.seed(0)
# x and y are the original data
n = 100
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+n/6 + np.random.randn(n)/10
# using .PolynomialFeatures and fit_transform to transform original data to degree 2
poly1 = PolynomialFeatures(degree=2)
x_D2_poly = poly1.fit_transform(x)
#check out their dimensions
x.shape
x_D2_poly.shape

但是,上述转换从 (100, 1) 的原始 x 返回了 (1, 5151) 的数组。这不是我所期望的。我无法弄清楚我的代码出了什么问题。如果有人能指出我的代码的错误或我的误解,那就太好了。我应该使用其他方法来转换原始数据吗?

谢谢。

真诚的,

[更新]因此,在我使用 x = x.reshape(-1, 1) 转换原始 x 后,Python 确实通过 poly1.fit_transform(x) 为我提供了所需的输出维度 (100, 1)。但是,当我执行 train_test_split、拟合数据并尝试获取预测值时:

x_poly1_train, x_poly1_test, y_train, y_test = train_test_split(x_poly1, y, random_state = 0)
linreg = LinearRegression().fit(x_poly1_train, y_train)
poly_predict = LinearRegression().predict(x)

Python 返回错误消息:

shapes (1,100) and (2,) not aligned: 100 (dim 1) != 2 (dim 0)

显然,我一定在某个地方又把维度问题弄错了。有人能解释一下吗?

谢谢。

最佳答案

我认为你需要像这样 reshape 你的x

x=x.reshape(-1,1)

你的 x 的形状是 (100,) 而不是 (100,1) 并且 fit_transform 需要 2 维。您获得 5151 个特征的原因是,您看到每个不同对 (100*99/2 = 4950) 一个特征,每个特征平方 (100) 一个特征,每个特征的一次幂 (100) 一个特征,和 1 的 0 次方 (1)。

对您编辑的问题的回复:您需要调用transform转换您想要预测的数据。

关于Python PolynomialFeatures 将数据转换为与原始数据不同的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44476338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com