我使用sklearn的PolynomialFeatures将数据预处理为各种度数转换,以便比较其模型拟合。 下面是我的代码:Python 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
然而,上述变换从的原始x返回的(1,5151)的阵列(100,1)。这不是我所期望的。我无法弄清楚我的代码有什么问题。如果有人能指出我的代码的错误或者我的错误概念,那将会很棒。 我应该使用替代方法来转换原始数据吗?
谢谢。
此致
[更新] 所以经过我用X = x.reshape(-1,1)来转换的原始x,Python不给我所需的输出尺寸(100,1)通过POLY1 .fit_transform(X)。然而,当我做了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)
显然,必须有某处我得到了尺寸错误的地方获得。任何人都可以对此有所了解吗?
谢谢。
我已经回答了您编辑的问题,但由于我确实回答了您的第一个问题,您是否介意接受答案? –
再次感谢。我很抱歉无法早日投票答复您,因为我对理解重塑()的事情有点专注......:p –