Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don’t provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove these features from the dataset. This process of removing redundant features and keeping only the necessary features in the dataset comes under the filter method of Feature Selection Methods.
Now Let’s see how we can remove constant features in Python.
Consider the self created dataset for the article:
Code: Create DataFrame of the above data
Code: Convert the categorical data to numerical data
Code: Fit the data to VarianceThreshold.
Output: Variance of different features:
[0.00000000e+00 6.17283951e-01 1.76746269e+07]
Code: Transform the data
[[2.000e+00 5.450e+02] [0.000e+00 1.505e+03] [0.000e+00 1.157e+03] [0.000e+00 2.541e+03] [1.000e+00 5.726e+03] [2.000e+00 3.125e+03] [0.000e+00 3.131e+03] [1.000e+00 6.525e+03] [1.000e+00 1.500e+04]] ********** Separator ********** Earlier shape of data: (9, 3) Shape after transformation: (9, 2)
As you can observe earlier we had 9 observations with 3 features.
After transformation we have 9 observations with 2 features. We can clearly observe that the removed feature is ‘Portal’.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course