SVM Practice: Breast Cancer Classification¶

Import Libraries¶

In [1]:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn import datasets
from sklearn import metrics

Import Dataset (one already built in to SKLearn)¶

Note: It's one I've worked on before, so EDA was not necessary

In [2]:
cancer = datasets.load_breast_cancer()
In [3]:
cancer.feature_names
Out[3]:
array(['mean radius', 'mean texture', 'mean perimeter', 'mean area',
       'mean smoothness', 'mean compactness', 'mean concavity',
       'mean concave points', 'mean symmetry', 'mean fractal dimension',
       'radius error', 'texture error', 'perimeter error', 'area error',
       'smoothness error', 'compactness error', 'concavity error',
       'concave points error', 'symmetry error',
       'fractal dimension error', 'worst radius', 'worst texture',
       'worst perimeter', 'worst area', 'worst smoothness',
       'worst compactness', 'worst concavity', 'worst concave points',
       'worst symmetry', 'worst fractal dimension'], dtype='<U23')
In [4]:
cancer.target_names
Out[4]:
array(['malignant', 'benign'], dtype='<U9')
In [5]:
cancer.data[0]
Out[5]:
array([1.799e+01, 1.038e+01, 1.228e+02, 1.001e+03, 1.184e-01, 2.776e-01,
       3.001e-01, 1.471e-01, 2.419e-01, 7.871e-02, 1.095e+00, 9.053e-01,
       8.589e+00, 1.534e+02, 6.399e-03, 4.904e-02, 5.373e-02, 1.587e-02,
       3.003e-02, 6.193e-03, 2.538e+01, 1.733e+01, 1.846e+02, 2.019e+03,
       1.622e-01, 6.656e-01, 7.119e-01, 2.654e-01, 4.601e-01, 1.189e-01])
In [6]:
cancer.target[0]

# 0:malignant, 1:benign
Out[6]:
0

Test_Train_Split¶

In [7]:
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, test_size=0.2)
In [8]:
classifier = SVC(kernel='linear')
In [9]:
classifier.fit(X_train, y_train)
Out[9]:
SVC(kernel='linear')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SVC(kernel='linear')

Accuracy Of Model¶

In [10]:
y_pred = classifier.predict(X_test)
In [11]:
print(metrics.accuracy_score(y_test, y_pred))
0.956140350877193

Confusion Matrix¶

In [12]:
test_conf_matrix = pd.DataFrame(
    metrics.confusion_matrix(y_test, y_pred), 
    index=['Actual 0:', 'Actual 1:'], 
    columns=['Predicted 0:', 'Predicted 1:']
)

print(test_conf_matrix)
           Predicted 0:  Predicted 1:
Actual 0:            40             2
Actual 1:             3            69

Classification Report¶

In [13]:
print(metrics.classification_report(y_test,y_pred))
              precision    recall  f1-score   support

           0       0.93      0.95      0.94        42
           1       0.97      0.96      0.97        72

    accuracy                           0.96       114
   macro avg       0.95      0.96      0.95       114
weighted avg       0.96      0.96      0.96       114

In [ ]: