1

From sklearn.model_selection family I have imported train_test_split and I want to train my model and test the model in order to predict variable y.

I assigned string data type as my X (features/variable of my dataset) and my y is an integer dataset (response).

After doing that I have imported LinearRegression function/method from sklearn.linear_model family, now when I try to fit the model it displays an error

can’t convert strings(X) to variable y

Why?

X = df[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area 
         Number of Rooms',
        'Avg. Area Number of Bedrooms', 'Area Population', 'Price', 
        'Address']]   
                                
y = df['Price']                                                                                                                    
from sklearn.model_selection import train_test_split 
 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.40 , random_state=101)         
from sklearn.linear_model import LinearRegression

lm = LinearRegression()                                                                                                        
lm.fit(X_train,y_train)
3
  • Please add the code that you have so far and maybe an excerpt of your data. It is very hard from this description to really give you a hint.
    – Christian
    Jul 11, 2022 at 10:07
  • Check out the codes Jul 11, 2022 at 10:34
  • 1
    Also show the complete traceback error. It is always super helpful. Jul 11, 2022 at 11:12

1 Answer 1

2

Make sure all the fields (both X and Y) are integer or float (basically they need to be numeric in nature. Linear Regression generates a linear expression of the form y = c1 * x1 + c2 * x2 + c3 * x3 + .... +c0. To apply values to such a formula for calculating predicted value or for generating the formula ALL the fields should be numeric.

2
  • Pls accept the answer if it worked for you :) Jul 11, 2022 at 11:26
  • In your example, "Address" looks like a problem. You can do many things : just drop it, reduce it to find the necessary info (ex : City, and then you put an Encoder on it to obtain information from it), calculate a value from it (ex : distance from the adress to a specific place, average salary of the city where the adress takes place, etc). But just don't put the address raw.
    – Adept
    Jul 11, 2022 at 14:21

Your Answer

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

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