Created
July 7, 2020 09:10
-
-
Save finlytics-hub/d830803764ff742edb3764a4d0d42bd6 to your computer and use it in GitHub Desktop.
Practical demonstration of KNNImputer with CV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# import required libraries | |
from sklearn.ensemble import RandomForestClassifier # can be any classifier of your choice | |
from sklearn.impute import KNNImputer | |
from sklearn.model_selection import cross_val_score | |
from sklearn.model_selection import RepeatedStratifiedKFold | |
from sklearn.pipeline import Pipeline | |
# define modeling pipeline | |
model = RandomForestClassifier() # can be any model that you want to use | |
imputer = KNNImputer() | |
pipeline = Pipeline(steps=[('i', imputer), ('m', model)]) | |
# define cross-validation criteria | |
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) | |
# fit and evaluate the model defined in pipeline with cross-validation as defined in cv | |
scores = cross_val_score(pipeline, X, y, scoring='accuracy', cv=cv) #use any scoring parameter of your choice | |
# print the mean accuracy score | |
print('Mean Accuracy: %.3f' % (np.mean(scores))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment