Linear SVC Sklearn - Training a Linear SVM Classification Model

Python

An example of training a linear SVM classification model using SVC from sklearn. Here we set the C parameter to 1, the kernel to 'linear' and the class_weight to 'balanced'.

If the model is overfitting then reduce the C value.

The balanced class weight parameter addresses issues with imbalanced training data.

 1|  from sklearn.svm import SVC
 2|  from sklearn.metrics import classification_report
 3|  
 4|  # create a linear SVC model with balanced class weights
 5|  model = SVC(C=1, kernel='linear', class_weight='balanced')
 6|  
 7|  # fit model
 8|  model.fit(X_train, y_train)
 9|  
10|  # make predictions on test data
11|  y_pred = model.predict(X_test)
12|  
13|  # create a dataframe of feature coefficients 
14|  coef = pd.DataFrame(model.coef_,columns=X_train.columns)
15|  print(coef)
16|  
17|  # print classification report
18|  print(classification_report(y_test, y_pred))
Did you find this snippet useful?

Sign up for free to to add this to your code library