fit, transform, and fit_transform. keeping the explanation so simple.
When we have two Arrays with different elements we use 'fit' and transform separately, we fit 'array 1' base on its internal function such as in MinMaxScaler (internal function is to find mean and standard deviation). For example, if we fit 'array 1' based on its mean and transform array 2, then the mean of array 1 will be applied to array 2 which we transformed. In simple words, we transform one array on the basic internal functions of another array.
Showing you with code;
import numpy as np
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
temperature = [32., np.nan, 28., np.nan, 32., np.nan, np.nan, 34., 40.]
windspeed = [ 6., 9., np.nan, 7., np.nan, np.nan, np.nan, 8., 12.]
n_arr_1 = np.array(temperature).reshape(3,3)
print('temperature:\n',n_arr_1)
n_arr_2 = np.array(windspeed).reshape(3,3)
print('windspeed:\n',n_arr_2)
Output:
temperature:
[[32. nan 28.]
[nan 32. nan]
[nan 34. 40.]]
windspeed:
[[ 6. 9. nan]
[ 7. nan nan]
[nan 8. 12.]]
fit and transform separately, transforming array 2 for fitted (based on mean) array 1;
imp.fit(n_arr_1)
imp.transform(n_arr_2)
Output
Check the output below, observe the output based on the previous two outputs you will see the difference. Basically, on Array 1 it is taking the mean of every column and fitting in array 2 according to its column where ever missing value is missed.
array([[ 6., 9., 34.],
[ 7., 33., 34.],
[32., 8., 12.]])
This is what we doing when we want to transform one array based on another array. but when we have a single array and we want to transform it based on its own mean. In this condition, we use fit_transform together.
See below;
imp.fit_transform(n_arr_2)
Output
array([[ 6. , 9. , 12. ],
[ 7. , 8.5, 12. ],
[ 6.5, 8. , 12. ]])
(Above) Alternativily we doing:
imp.fit(n_arr_2)
imp.transform(n_arr_2)
Output
array([[ 6. , 9. , 12. ],
[ 7. , 8.5, 12. ],
[ 6.5, 8. , 12. ]])
Why we fitting and transforming the same array separately, it takes two line code, why don't we use simple fit_transform
which can fit and transform the same array in one line code. That's what the difference is between fit and transform and fit_transform
.
Check this Google Colab link, you can run it by yourself, and can understand it well.
fit
on thetraining dataset
and use thetransform
method onboth
- the training dataset and the test dataset $\endgroup$