0

I'm trying to write one generic function to run most sklearn models that I can use to quickly explore different models in one line. The below code works if I replace leaf_size=30, n_neighbors=6 with a number. It seems to expect the first argument to be n_neighbors and requires a number. I want to be able to pass the function two pieces of information: a) the model name b) one string that contains all of the parameters I want to pass to the model.

Is there something simple I'm missing or is this not possible?

def sklearn_mod(mod_name,param_list):
    mod = mod_name(param_list)
    mod.fit(features_train, target_train)
    print(mod)
    expected = target_test
    predicted_mod = mod.predict(features_test)
    print('-----')
    print "Accuracy of Model:", accuracy_score(target_test, predicted_mod)
    print('-----')
    print(classification_report(target_test, predicted_mod))
    y_pred = predicted_mod
    y_true = expected
    print(confusion_matrix(y_true, y_pred))
    print('-----')
    print('Cross Validation:')
    scores = cross_val_score(mod, features_train, target_train, cv=10)
    print(scores)
    print"Mean CV Accuracy:",scores.mean()
    print('-----');

sklearn_mod(KNeighborsClassifier,'leaf_size=30, n_neighbors=6')
1
  • I think I was making this too hard. I think this will work better with just one parameter value in my defined function. I think it will work better to just call it like this: sklearn_mod(KNeighborsClassifier(n_neighbors=6, leaf_size=30)) Commented Nov 22, 2016 at 3:23

1 Answer 1

1

You wouldn't want to pass in a csv string as your parameter, but you can use **kwargs.

Create a dict with the parameter name and value, and then pass that into your function prepended with **.

For example:

params = {'leaf_size': 30, 'n_neighbors': 6}
sklearn_mod(KNeighborsClassifier, **params)
Sign up to request clarification or add additional context in comments.

1 Comment

Should add how the first two lines of sklear_mod are supposed to look, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.