Python PolynomialFeatures 将数据转换为与原始数据不同的形状
Python PolynomialFeatures transforms data into different shape from the original one
我正在使用 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
但是上面的转换从原来的x(100, 1)返回了一个(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)
显然,我一定是在什么地方又弄错了维度的问题。任何人都可以对此有所了解吗?
谢谢。
我认为你需要像这样重塑你的 x
x=x.reshape(-1,1)
你的 x 的形状是 (100,) 而不是 (100,1) 并且 fit_transform 需要 2 个维度。
您获得 5151 个特征的原因是您看到每个不同对 (100*99/2 = 4950) 一个特征,每个特征平方 (100) 一个特征,每个特征 (100) 的第一个幂一个特征,和 0 次方 (1).
对您修改后的问题的回复:
您需要调用 transform 来转换您希望预测的数据。
我正在使用 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
但是上面的转换从原来的x(100, 1)返回了一个(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)
显然,我一定是在什么地方又弄错了维度的问题。任何人都可以对此有所了解吗?
谢谢。
我认为你需要像这样重塑你的 x
x=x.reshape(-1,1)
你的 x 的形状是 (100,) 而不是 (100,1) 并且 fit_transform 需要 2 个维度。 您获得 5151 个特征的原因是您看到每个不同对 (100*99/2 = 4950) 一个特征,每个特征平方 (100) 一个特征,每个特征 (100) 的第一个幂一个特征,和 0 次方 (1).
对您修改后的问题的回复: 您需要调用 transform 来转换您希望预测的数据。