Linear regression throws ValueError and UserWarning

Viewed 49

I was writing a python program to predict the price of a house by given area:

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
import pandas as pd


df = pd.read_csv('traindata.csv')
plt.xlabel('area')

plt.ylabel('price')

plt.scatter(df.area,df.price)


reg = linear_model.LinearRegression()

reg.fit(df[['area']], df.price)

reg.predict(33000)

When was executing the program, it showed that

raise ValueError(
ValueError: Expected 2D array, got scalar array instead:
array=33000.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Then I changed the (33000) to ([[33000]]) and it showed

UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn(.

Then I changed it to ([['33000']]) and still showed the same error.

1 Answers

You cannot use ([['33000']]) because you will be trying to predict with a string value, which doesn't work.

If you are worried about the warning, you can create a data frame on the fly, for example :

import pandas as pd
import numpy as np
from sklearn import linear_model

df = pd.DataFrame({'area':np.random.randint(10000,40000,100),
'price':np.random.uniform(1,100,100)})

reg = linear_model.LinearRegression()

reg.fit(df[['area']], df.price)

reg.predict(pd.DataFrame({'area':[33000]}))
array([53.70626723])

But you can see that it's the same as if you do :

reg.predict([[33000]])
/Users/gen/anaconda3/lib/python3.8/site-packages/sklearn/base.py:445: UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names
  warnings.warn(
Out[15]: array([53.70626723])
Related