## ## As always, start with the documentation and try to reproduce the ## results there: ## ## http://scikit-learn.org/stable/modules/svm.html ## ## Goal: train and tune an SVM on a new data set. from sklearn.svm import SVC ## 1. download the data (predict Leukemia from a set of gene expression data): from sklearn.datasets import fetch_mldata leuk = fetch_mldata('leukemia', data_home='./') ## check a basic classifier - just to have an idea of its performance clf = SVC(...put your favourite parameters here...) clf.fit(leuk.data, leuk.target) ## 2. We want to find the best parameters for our classifier. Let's ## try "grid search": for a number of combinations of parameters, we ## estimate the performance and choose the best combination. from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report X_train, X_test, y_train, y_test = train_test_split(leuk.data, leuk.target, test_size=0.25, random_state=0) # Set the parameters by cross-validation tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] scores = ['accuracy', 'roc_auc'] for score in scores: print("# Tuning hyper-parameters for %s" % score) print() clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=3, scoring=score) clf.fit(X_train, y_train) print("Best parameters set found on development set:") print() print(clf.best_estimator_) print() print("Grid scores on development set:") print() for params, mean_score, scores in clf.grid_scores_: print("%0.3f (+/-%0.03f) for %r" % (mean_score, scores.std() / 2, params)) print() print("Detailed classification report:") print() print("The model is trained on the full development set.") print("The scores are computed on the full evaluation set.") print() y_true, y_pred = y_test, clf.predict(X_test) print(classification_report(y_true, y_pred)) print() ## ## TODO: try another approach to parameter tuning: ## check the random search method (3.2.2 at http://scikit-learn.org/stable/modules/grid_search.html ) ## and use it!