|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +====================================================== |
| 6 | +Effect of transforming the targets in regression model |
| 7 | +====================================================== |
| 8 | +
|
| 9 | +In this example, we give an overview of the |
| 10 | +:class:`sklearn.preprocessing.TransformedTargetRegressor`. Two examples |
| 11 | +illustrate the benefit of transforming the targets before learning a linear |
| 12 | +regression model. The first example uses synthetic data while the second |
| 13 | +example is based on the Boston housing data set. |
| 14 | +
|
| 15 | +""" |
| 16 | + |
| 17 | +# Author: Guillaume Lemaitre <[email protected]> |
| 18 | +# License: BSD 3 clause |
| 19 | + |
| 20 | +from __future__ import print_function, division |
| 21 | + |
| 22 | +import numpy as np |
| 23 | +import matplotlib.pyplot as plt |
| 24 | + |
| 25 | +print(__doc__) |
| 26 | + |
| 27 | +############################################################################### |
| 28 | +# Synthetic example |
| 29 | +############################################################################### |
| 30 | + |
| 31 | +from sklearn.datasets import make_regression |
| 32 | +from sklearn.model_selection import train_test_split |
| 33 | +from sklearn.linear_model import RidgeCV |
| 34 | +from sklearn.preprocessing import TransformedTargetRegressor |
| 35 | +from sklearn.metrics import median_absolute_error, r2_score |
| 36 | + |
| 37 | +############################################################################### |
| 38 | +# A synthetic random regression problem is generated. The targets ``y`` are |
| 39 | +# modified by: (i) translating all targets such that all entries are |
| 40 | +# non-negative and (ii) applying an exponential function to obtain non-linear |
| 41 | +# targets which cannot be fitted using a simple linear model. |
| 42 | +# |
| 43 | +# Therefore, a logarithmic and an exponential function will be used to |
| 44 | +# transform the targets before training a linear regression model and using it |
| 45 | +# for prediction. |
| 46 | + |
| 47 | + |
| 48 | +def log_transform(x): |
| 49 | + return np.log(x + 1) |
| 50 | + |
| 51 | + |
| 52 | +def exp_transform(x): |
| 53 | + return np.exp(x) - 1 |
| 54 | + |
| 55 | + |
| 56 | +X, y = make_regression(n_samples=10000, noise=100, random_state=0) |
| 57 | +y = np.exp((y + abs(y.min())) / 200) |
| 58 | +y_trans = log_transform(y) |
| 59 | + |
| 60 | +############################################################################### |
| 61 | +# The following illustrate the probability density functions of the target |
| 62 | +# before and after applying the logarithmic functions. |
| 63 | + |
| 64 | +f, (ax0, ax1) = plt.subplots(1, 2) |
| 65 | + |
| 66 | +ax0.hist(y, bins='auto', normed=True) |
| 67 | +ax0.set_xlim([0, 2000]) |
| 68 | +ax0.set_ylabel('Probability') |
| 69 | +ax0.set_xlabel('Target') |
| 70 | +ax0.set_title('Target distribution') |
| 71 | + |
| 72 | +ax1.hist(y_trans, bins='auto', normed=True) |
| 73 | +ax1.set_ylabel('Probability') |
| 74 | +ax1.set_xlabel('Target') |
| 75 | +ax1.set_title('Transformed target distribution') |
| 76 | + |
| 77 | +f.suptitle("Synthetic data", y=0.035) |
| 78 | +f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95]) |
| 79 | + |
| 80 | +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) |
| 81 | + |
| 82 | +############################################################################### |
| 83 | +# At first, a linear model will be applied on the original targets. Due to the |
| 84 | +# non-linearity, the model trained will not be precise during the |
| 85 | +# prediction. Subsequently, a logarithmic function is used to linearize the |
| 86 | +# targets, allowing better prediction even with a similar linear model as |
| 87 | +# reported by the median absolute error (MAE). |
| 88 | + |
| 89 | +f, (ax0, ax1) = plt.subplots(1, 2, sharey=True) |
| 90 | + |
| 91 | +regr = RidgeCV() |
| 92 | +regr.fit(X_train, y_train) |
| 93 | +y_pred = regr.predict(X_test) |
| 94 | + |
| 95 | +ax0.scatter(y_test, y_pred) |
| 96 | +ax0.plot([0, 2000], [0, 2000], '--k') |
| 97 | +ax0.set_ylabel('Target predicted') |
| 98 | +ax0.set_xlabel('True Target') |
| 99 | +ax0.set_title('Ridge regression \n without target transformation') |
| 100 | +ax0.text(100, 1750, r'$R^2$=%.2f, MAE=%.2f' % ( |
| 101 | + r2_score(y_test, y_pred), median_absolute_error(y_test, y_pred))) |
| 102 | +ax0.set_xlim([0, 2000]) |
| 103 | +ax0.set_ylim([0, 2000]) |
| 104 | + |
| 105 | +regr_trans = TransformedTargetRegressor(regressor=RidgeCV(), |
| 106 | + func=log_transform, |
| 107 | + inverse_func=exp_transform) |
| 108 | +regr_trans.fit(X_train, y_train) |
| 109 | +y_pred = regr_trans.predict(X_test) |
| 110 | + |
| 111 | +ax1.scatter(y_test, y_pred) |
| 112 | +ax1.plot([0, 2000], [0, 2000], '--k') |
| 113 | +ax1.set_ylabel('Target predicted') |
| 114 | +ax1.set_xlabel('True Target') |
| 115 | +ax1.set_title('Ridge regression \n with target transformation') |
| 116 | +ax1.text(100, 1750, r'$R^2$=%.2f, MAE=%.2f' % ( |
| 117 | + r2_score(y_test, y_pred), median_absolute_error(y_test, y_pred))) |
| 118 | +ax1.set_xlim([0, 2000]) |
| 119 | +ax1.set_ylim([0, 2000]) |
| 120 | + |
| 121 | +f.suptitle("Synthetic data", y=0.035) |
| 122 | +f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95]) |
| 123 | + |
| 124 | +############################################################################### |
| 125 | +# Real-world data set |
| 126 | +############################################################################### |
| 127 | + |
| 128 | +############################################################################### |
| 129 | +# In a similar manner, the boston housing data set is used to show the impact |
| 130 | +# of transforming the targets before learning a model. In this example, the |
| 131 | +# targets to be predicted corresponds to the weighted distances to the five |
| 132 | +# Boston employment centers. |
| 133 | + |
| 134 | +from sklearn.datasets import load_boston |
| 135 | +from sklearn.preprocessing import QuantileTransformer, quantile_transform |
| 136 | + |
| 137 | +dataset = load_boston() |
| 138 | +target = np.array(dataset.feature_names) == "DIS" |
| 139 | +X = dataset.data[:, np.logical_not(target)] |
| 140 | +y = dataset.data[:, target].squeeze() |
| 141 | +y_trans = quantile_transform(dataset.data[:, target], |
| 142 | + output_distribution='normal').squeeze() |
| 143 | + |
| 144 | +############################################################################### |
| 145 | +# A :class:`sklearn.preprocessing.QuantileTransformer` is used such that the |
| 146 | +# targets follows a normal distribution before applying a |
| 147 | +# :class:`sklearn.linear_model.RidgeCV` model. |
| 148 | + |
| 149 | +f, (ax0, ax1) = plt.subplots(1, 2) |
| 150 | + |
| 151 | +ax0.hist(y, bins='auto', normed=True) |
| 152 | +ax0.set_ylabel('Probability') |
| 153 | +ax0.set_xlabel('Target') |
| 154 | +ax0.set_title('Target distribution') |
| 155 | + |
| 156 | +ax1.hist(y_trans, bins='auto', normed=True) |
| 157 | +ax1.set_ylabel('Probability') |
| 158 | +ax1.set_xlabel('Target') |
| 159 | +ax1.set_title('Transformed target distribution') |
| 160 | + |
| 161 | +f.suptitle("Boston housing data: distance to employment centers", y=0.035) |
| 162 | +f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95]) |
| 163 | + |
| 164 | +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) |
| 165 | + |
| 166 | +############################################################################### |
| 167 | +# The effect of the transformer is weaker than on the synthetic data. However, |
| 168 | +# the transform induces a decrease of the MAE. |
| 169 | + |
| 170 | +f, (ax0, ax1) = plt.subplots(1, 2, sharey=True) |
| 171 | + |
| 172 | +regr = RidgeCV() |
| 173 | +regr.fit(X_train, y_train) |
| 174 | +y_pred = regr.predict(X_test) |
| 175 | + |
| 176 | +ax0.scatter(y_test, y_pred) |
| 177 | +ax0.plot([0, 10], [0, 10], '--k') |
| 178 | +ax0.set_ylabel('Target predicted') |
| 179 | +ax0.set_xlabel('True Target') |
| 180 | +ax0.set_title('Ridge regression \n without target transformation') |
| 181 | +ax0.text(1, 9, r'$R^2$=%.2f, MAE=%.2f' % ( |
| 182 | + r2_score(y_test, y_pred), median_absolute_error(y_test, y_pred))) |
| 183 | +ax0.set_xlim([0, 10]) |
| 184 | +ax0.set_ylim([0, 10]) |
| 185 | + |
| 186 | +regr_trans = TransformedTargetRegressor( |
| 187 | + regressor=RidgeCV(), |
| 188 | + transformer=QuantileTransformer(output_distribution='normal')) |
| 189 | +regr_trans.fit(X_train, y_train) |
| 190 | +y_pred = regr_trans.predict(X_test) |
| 191 | + |
| 192 | +ax1.scatter(y_test, y_pred) |
| 193 | +ax1.plot([0, 10], [0, 10], '--k') |
| 194 | +ax1.set_ylabel('Target predicted') |
| 195 | +ax1.set_xlabel('True Target') |
| 196 | +ax1.set_title('Ridge regression \n with target transformation') |
| 197 | +ax1.text(1, 9, r'$R^2$=%.2f, MAE=%.2f' % ( |
| 198 | + r2_score(y_test, y_pred), median_absolute_error(y_test, y_pred))) |
| 199 | +ax1.set_xlim([0, 10]) |
| 200 | +ax1.set_ylim([0, 10]) |
| 201 | + |
| 202 | +f.suptitle("Boston housing data: distance to employment centers", y=0.035) |
| 203 | +f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95]) |
| 204 | + |
| 205 | +plt.show() |
0 commit comments