Effect of transforming the targets in regression model
In this example, we give an overview of
TransformedTargetRegressor. We use two examples
to illustrate the benefit of transforming the targets before learning a linear
regression model. The first example uses synthetic data while the second
example is based on the Ames housing data set.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Synthetic example
A synthetic random regression dataset is generated. The targets y are
modified by:
translating all targets such that all entries are
non-negative (by adding the absolute value of the lowest ) and
y
applying an exponential function to obtain non-linear
targets which cannot be fitted using a simple linear model.
Therefore, a logarithmic (np.log1p) and an exponential function
(np.expm1) will be used to transform the targets before training a linear
regression model and using it for prediction.
At first, a linear model will be applied on the original targets. Due to the
non-linearity, the model trained will not be precise during
prediction. Subsequently, a logarithmic function is used to linearize the
targets, allowing better prediction even with a similar linear model as
reported by the median absolute error (MedAE).
fromsklearn.composeimportTransformedTargetRegressorfromsklearn.linear_modelimportRidgeCVfromsklearn.metricsimportPredictionErrorDisplayf,(ax0,ax1)=plt.subplots(1,2,sharey=True)ridge_cv=RidgeCV().fit(X_train,y_train)y_pred_ridge=ridge_cv.predict(X_test)ridge_cv_with_trans_target=TransformedTargetRegressor(regressor=RidgeCV(),func=np.log1p,inverse_func=np.expm1).fit(X_train,y_train)y_pred_ridge_with_trans_target=ridge_cv_with_trans_target.predict(X_test)PredictionErrorDisplay.from_predictions(y_test,y_pred_ridge,kind="actual_vs_predicted",ax=ax0,scatter_kwargs={"alpha":0.5},)PredictionErrorDisplay.from_predictions(y_test,y_pred_ridge_with_trans_target,kind="actual_vs_predicted",ax=ax1,scatter_kwargs={"alpha":0.5},)# Add the score in the legend of each axisforax,y_predinzip([ax0,ax1],[y_pred_ridge,y_pred_ridge_with_trans_target]):forname,scoreincompute_score(y_test,y_pred).items():ax.plot([],[]," ",label=f"{name}={score}")ax.legend(loc="upper left")ax0.set_title("Ridge regression \n without target transformation")ax1.set_title("Ridge regression \n with target transformation")f.suptitle("Synthetic data",y=1.05)plt.tight_layout()
Real-world data set
In a similar manner, the Ames housing data set is used to show the impact
of transforming the targets before learning a model. In this example, the
target to be predicted is the selling price of each house.
fromsklearn.datasetsimportfetch_openmlfromsklearn.preprocessingimportquantile_transformames=fetch_openml(name="house_prices",as_frame=True)# Keep only numeric columnsX=ames.data.select_dtypes(np.number)# Remove columns with NaN or Inf valuesX=X.drop(columns=["LotFrontage","GarageYrBlt","MasVnrArea"])# Let the price be in k$y=ames.target/1000y_trans=quantile_transform(y.to_frame(),n_quantiles=900,output_distribution="normal",copy=True).squeeze()
The effect of the transformer is weaker than on the synthetic data. However,
the transformation results in an increase in R2 and large decrease
of the MedAE. The residual plot (predicted target - true target vs predicted
target) without target transformation takes on a curved, ‘reverse smile’
shape due to residual values that vary depending on the value of predicted
target. With target transformation, the shape is more linear indicating
better model fit.