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

我使用sklearn的PolynomialFeatures对数据进行不同程度的预处理,以比较它们的模型拟合效果。以下是我的代码:

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

然而,上述转换返回了一个形状为(1, 5151)的数组,而原始的x是(100, 1)。这并不是我期望的结果。我无法找出我的代码有什么问题。如果有人能指出我的代码错误或我的误解,那就太好了。我应该使用其他方法来转换原始数据吗?

谢谢你。

此致,

[更新]在我使用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)

显然,我再次在维度上犯了错误。谁能帮我解答这个问题?

谢谢你。


回答:

我想你需要像这样重塑你的x:

x=x.reshape(-1,1)

你的x的形状是(100,)而不是(100,1),而fit_transform期望的是2维。你得到5151个特征的原因是,你看到的是每个不同对的一个特征(100*99/2 = 4950),每个特征平方的一个特征(100),每个特征的一次幂的一个特征(100),以及零次幂的一个特征(1)。

对你编辑后的问题回应:你需要调用transform来转换你希望预测的数据。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注