Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. from sklearn.svm import SVC
  2. from time import time
  3. from sklearn.metrics import f1_score
  4.  
  5. def train_classifier(clf, X_train, y_train):
  6. ''' Fits a classifier to the training data. '''
  7.  
  8. # Start the clock, train the classifier, then stop the clock
  9. start = time()
  10. clf.fit(X_train, y_train)
  11. end = time()
  12.  
  13. # Print the results
  14. print("Trained model in {:.4f} seconds".format(end - start))
  15.  
  16.  
  17. def predict_labels(clf, features, target):
  18. ''' Makes predictions using a fit classifier based on F1 score. '''
  19.  
  20. # Start the clock, make predictions, then stop the clock
  21. start = time()
  22. y_pred = clf.predict(features)
  23.  
  24. end = time()
  25. # Print and return results
  26. print("Made predictions in {:.4f} seconds.".format(end - start))
  27.  
  28. return f1_score(target, y_pred, labels=[0, 1], average='micro'), sum(target == y_pred) / float(len(y_pred))
  29.  
  30.  
  31. def train_predict(clf, X_train, y_train, X_test, y_test):
  32. ''' Train and predict using a classifer based on F1 score. '''
  33.  
  34. # Indicate the classifier and the training set size
  35. print("Training a {} using a training set size of {}. . .".format(
  36. clf.__class__.__name__, len(X_train)))
  37.  
  38. # Train the classifier
  39. train_classifier(clf, X_train, y_train)
  40.  
  41. # Print the results of prediction for both training and testing
  42. f1, acc = predict_labels(clf, X_train, y_train)
  43. print (f1, acc)
  44. print("F1 score and accuracy score for training set: {:.4f} , {:.4f}.".format(
  45. f1, acc))
  46.  
  47. f1, acc = predict_labels(clf, X_test, y_test)
  48. print("F1 score and accuracy score for test set: {:.4f} , {:.4f}.".format(
  49. f1, acc))
  50.  
  51. from sklearn.externals import joblib
  52.  
  53. filename = 'finalized_model.sav'
  54. joblib.dump(clf, filename)
  55.  
  56.  
  57. clf_B = SVC(random_state=912, kernel='rbf')
  58. train_predict(clf_B, X_train, y_train, X_test, y_test)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement