Search code examples
pythonpandasmachine-learningscikit-learnlinear-regression

sklearn mutiple linear regression --> dtype error


I'm trying to predict a value using a linear regression model. However, when I use .predict from sklearn I can't find a way to plug in the data for X without getting a data type error.

from sklearn import linear_model

KitchenQual_X = KitchenQual_df[["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea"]]
KitchenQual_Y = KitchenQual_df["dummy_KitchenQual"]

regr_KitchenQual = linear_model.LinearRegression()
regr_KitchenQual.fit(KitchenQual_X, KitchenQual_Y)

print("Predicted missing KitchenQual value: " + regr_KitchenQual.predict(df_both[["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea"]].loc[[1555]]))

When running the code in my kaggle notebook I receive the following error:

---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
<ipython-input-206-1f022a48e21c> in <module>
----> 1 print("Predicted missing KitchenQual value: " + regr_KitchenQual.predict(df_both[["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea"]].loc[[1555]]))

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U37'), dtype('<U37')) -> dtype('<U37')

I would appreciate any help :)


Solution

  • Assuming your dependent variable is continuous, using an example data and repeating your steps:

    from sklearn import linear_model
    import numpy as np
    import pandas as pd
    
    KitchenQual_df = pd.DataFrame(np.random.normal(0,1,(2000,6)))
    KitchenQual_df.columns = ["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea","dummy_KitchenQual"]
    
    KitchenQual_X = KitchenQual_df[["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea"]]
    KitchenQual_Y = KitchenQual_df["dummy_KitchenQual"]
    
    regr_KitchenQual = linear_model.LinearRegression()
    regr_KitchenQual.fit(KitchenQual_X, KitchenQual_Y)
    
    pred = regr_KitchenQual.predict(KitchenQual_df[["OverallQual", "YearBuilt", "YearRemodAdd", "GarageCars", "GarageArea"]].loc[[1555]])
    

    The prediction is an array and you cannot just concatenate a string and an array using +, these negative example below gives you the same error in the question:

    "a" + np.array(['b','c'])
    "a" + np.array([1,2])
    
    UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U1'), dtype('<U1')) -> dtype('<U1')
    

    You can do:

    print("Predicted missing KitchenQual value: " + str(pred[0]))
    
    Predicted missing KitchenQual value: -0.11176904834490986