Sklearn error : predict(x,y) takes 2 positional arguments but 3 were given

GD_N picture GD_N · Oct 3, 2017 · Viewed 12.7k times · Source

I am working on building a multivariate regression analysis on sklearn , I did a thorough look at the documentation. When I run the predict() function I get the error : predict() takes 2 positional arguments but 3 were given

X is a data frame , y is column; I have tried to convert the data frame to array / matrix but still get the error.

Have added a snippet showing the x and y arrays.

reg.coef_
reg.predict(x,y)

x_train=train.drop('y-variable',axis =1)
y_train=train['y-variable']

x_test=test.drop('y-variable',axis =1)
y_test=test['y-variable']


x=x_test.as_matrix()
y=y_test.as_matrix()

reg = linear_model.LinearRegression()
reg.fit(x_train,y_train)

reg.predict(x,y)

Answer

Mohamed Ali JAMAOUI picture Mohamed Ali JAMAOUI · Oct 3, 2017

Use reg.predict(x). You don't need to provide the y values to predict. In fact, the purpose of training the machine learning model is to let it infer the values of y given the input parameters in x.

Also, the documentation of predict here explains that predict expects only x as a parameter.

The reason why you get the error:

predict() takes 2 positional arguments but 3 were given

is because, when you call reg.predic(x), python will implicitly translate this to reg.predict(self,x), that's why the error is telling you that predict() takes 2 positional arguments. The way you call predict, reg.predict(x,y), will be translated to reg.predict(self,x,y) thus 3 positional arguments will be used instead of 2 and that explains the whole error message.