Sanyam Garg
Sanyam Garg

Reputation: 11

Error in using predict function in Simple Regression Model (Shapes not aligned)

Can anyone please help me out in solving the above error. I was actually using predict function in Simple Regression Model used in Machine Learning, and came up with an error. I have already used the reshape function to transform my test and train data and used them accordingly. The code executed is:-

   import pandas  as pd
   from numpy import *
   import matplotlib.pyplot as plt
   dataset=pd.read_csv("Salary_Data.csv")
   X=dataset.iloc[:,0].values
   X
   Y=dataset.iloc[:,1].values
   dataset.isnull()
   from sklearn.impute import SimpleImputer
   imputer=SimpleImputer(missing_values="NaN",strategy="mean",verbose=0)
   from sklearn.model_selection import train_test_split
   X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=1/3,random_state=0)
   x_train=X_train.reshape(1,-1)
   X_train
   x_train
   y_train=Y_train.reshape(1,-1)
   Y_test
   from sklearn.linear_model import LinearRegression
   regressor=LinearRegression()
   X_train
   LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
   x_test=X_test.reshape(-1,1)
   x_test
   y_test=Y_test.reshape(-1,1)
   y_test
   x_train
   regressor.fit(x_train,y_train)
   x_test
   y_pred=regressor.predict(x_test)

The error is:

ValueError                                Traceback (most recent call last)
<ipython-input-42-350ddd5e0bb0> in <module>()
----> 1 y_pred=regressor.predict(x_test)

2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/extmath.py in safe_sparse_dot(a, b, dense_output)
    140         return ret
    141     else:
--> 142         return np.dot(a, b)
    143 
    144 

<__array_function__ internals> in dot(*args, **kwargs)

ValueError: shapes (10,1) and (20,20) not aligned: 1 (dim 1) != 20 (dim 0) 

Upvotes: 0

Views: 86

Answers (1)

kathir raja
kathir raja

Reputation: 1016

The dimension to the model is wrong (ie) you have reshaped with (1,-1) instead of (-1,1)

change the following lines

x_train=X_train.reshape(1,-1) // your code Change to bellow code
x_train=X_train.reshape(-1,1) 
...
y_train=Y_train.reshape(1,-1)// your code Change to bellow code
y_train=Y_train.reshape(-1,1)

I hope this works for you

Upvotes: 1

Related Questions