Skip to content

Instantly share code, notes, and snippets.

@finlytics-hub
Created July 7, 2020 09:10
Show Gist options
  • Save finlytics-hub/d830803764ff742edb3764a4d0d42bd6 to your computer and use it in GitHub Desktop.
Save finlytics-hub/d830803764ff742edb3764a4d0d42bd6 to your computer and use it in GitHub Desktop.
Practical demonstration of KNNImputer with CV
# 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