How to use SVM Classifier and Regressor in Python?
0

How to use SVM Classifier and Regressor in Python?

This recipe helps you use SVM Classifier and Regressor in Python
In [2]:
## How to use SVM Classifier and Regressor in Python
def Snippet_170():
    print()
    print(format('How to use SVM Classifier and Regressor in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    from sklearn import datasets
    from sklearn import metrics
    from sklearn.model_selection import train_test_split
    import matplotlib.pyplot as plt
    import seaborn as sns

    plt.style.use('ggplot')

    from sklearn.svm import SVC, SVR

    # load the iris datasets
    dataset = datasets.load_breast_cancer()
    X = dataset.data; y = dataset.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

    # fit a SVM model to the data
    model = SVC()
    model.fit(X_train, y_train)
    print(); print(model)

    # make predictions
    expected_y  = y_test
    predicted_y = model.predict(X_test)

    # summarize the fit of the model
    print(); print(metrics.classification_report(expected_y, predicted_y))
    print(); print(metrics.confusion_matrix(expected_y, predicted_y))

    # load the boston datasets
    dataset = datasets.load_boston()
    X = dataset.data; y = dataset.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

    # fit a SVM model to the data
    model = SVR()
    model.fit(X_train, y_train)
    print(); print(model)

    # make predictions
    expected_y  = y_test
    predicted_y = model.predict(X_test)

    # summarize the fit of the model
    print(); print(metrics.r2_score(expected_y, predicted_y))
    print(); print(metrics.mean_squared_log_error(expected_y, predicted_y))
    plt.figure(figsize=(10,10))
    sns.regplot(expected_y, predicted_y, fit_reg=True, scatter_kws={"s": 100})

Snippet_170()
****************How to use SVM Classifier and Regressor in Python*****************

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)

              precision    recall  f1-score   support

           0       0.00      0.00      0.00        61
           1       0.57      1.00      0.73        82

   micro avg       0.57      0.57      0.57       143
   macro avg       0.29      0.50      0.36       143
weighted avg       0.33      0.57      0.42       143


[[ 0 61]
 [ 0 82]]

SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.1,
  gamma='auto_deprecated', kernel='rbf', max_iter=-1, shrinking=True,
  tol=0.001, verbose=False)

0.00801027393111986

0.12265173265939316