I am working on a model which predicts car prices by their attributes. I have noticed that the predictions of LinearRegression model differ depending on the type of input (numpy.ndarray, scipy.sparse.csr.csr_matrix).
My data consists of a few numerical and categorical attributes, there are no NaNs.
This is a simple data preparation code (it is common for every case I describe later):
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
# Splitting to test and train
X = data_orig.drop("price", axis=1)
y = data_orig[["price"]]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Numerical attributes pipeline
num_pipeline = Pipeline([ ("scaler", StandardScaler()) ])
# Categorical attributes pipeline
cat_pipeline = Pipeline([ ("encoder", OneHotEncoder(handle_unknown="ignore")) ])
# Complete pipeline
full_pipeline = ColumnTransformer([
("cat", cat_pipeline, ["model", "transmission", "fuelType"]),
("num", num_pipeline, ["year", "mileage", "tax", "mpg", "engineSize"]),
])
Let's build a LinearRegression model (X_train and X_test will be instances of scipy.sparse.csr.csr_matrix):
...
X_train = full_pipeline.fit_transform(X_train)
X_test = full_pipeline.transform(X_test)
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression().fit(X_train, y_train)
pred = lin_reg.predict(X_test)
r2_score(y_test, pred) # 0.896044623680753 OK
If I convert X_test and X_train to the numpy.ndarray, the predictions of the model are completely incorrect:
...
X_train = full_pipeline.fit_transform(X_train).toarray() # Here
X_test = full_pipeline.transform(X_test).toarray() # And here
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression().fit(X_train, y_train)
pred = lin_reg.predict(X_test)
r2_score(y_test, pred) # -7.919935999010152e+19 Something is wrong
I also tested DecisionTreeRegressor, RandomForestRegressor and SVR but the problem occurs only with LinearRegression.

