0
$\begingroup$

I am trying to predict the target variable and finding the difference from actual variable using polynomial regression. However predicted variable is an array of 3 dimension with the shape as (13159,3) and actual targetvariable is of size (13159,). How can I get the compatible target variable to get the difference from predicted and actual variable. Below is the code snippet.

polynomial_features= PolynomialFeatures(degree=1)
x_poly = polynomial_features.fit_transform(X_train)
y_poly = polynomial_features.fit_transform(y_train)
x_poly_test = polynomial_features.fit_transform(X_test)
y_poly_test = polynomial_features.fit_transform(y_test)


model = LinearRegression()
model.fit(x_poly, y_poly)
r_sq = model.score(x_poly_test, y_poly_test)

y_predict= model.predict(x_poly_test)

y_actual=y_test["Target variable"].to_numpy()

diff_value= y_predict - y_actual
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[32], line 1
----> 1 diff_value= y_predict - y_actual

ValueError: operands could not be broadcast together with shapes (13159,3) (13159,) 
$\endgroup$

1 Answer 1

0
$\begingroup$

The issue in this code is that PolynomialFeatures transformation is being applied to the target variable y_train and y_test. This is not correct because PolynomialFeatures is used for feature expansion, it should only be applied on the features (X_train and X_test) not on the target variable.

Also, when you are using LinearRegression model's fit method, it expects 2D array-like for X_train and 1D array-like for y_train. But here, since you have transformed y_train into polynomial features which makes it a 2D array, this will cause an error.

Try the following:

polynomial_features= PolynomialFeatures(degree=1)
x_poly = polynomial_features.fit_transform(X_train)
x_poly_test = polynomial_features.transform(X_test)

model = LinearRegression()
model.fit(x_poly, y_train)
r_sq = model.score(x_poly_test, y_test)

y_predict= model.predict(x_poly_test)

y_actual=y_test["Target variable"].to_numpy()

diff_value= y_predict - y_actual
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.