我使用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来转换你希望预测的数据。