6 분 소요

[Notice] [ML_7]

Classification(breast_cancer data)

import warnings

# Avoid unnecessary warning output.
warnings.filterwarnings('ignore')
import pandas as pd
import seaborn as sns
from IPython.display import Image

Error

The pitfall of accuracy

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import numpy as np

target: 0: malignant tumor, 1: benign tumor

cancer = load_breast_cancer()
print(cancer['DESCR'])
.. _breast_cancer_dataset:

Breast cancer wisconsin (diagnostic) dataset
--------------------------------------------

**Data Set Characteristics:**

    :Number of Instances: 569

    :Number of Attributes: 30 numeric, predictive attributes and the class

    :Attribute Information:
        - radius (mean of distances from center to points on the perimeter)
        - texture (standard deviation of gray-scale values)
        - perimeter
        - area
        - smoothness (local variation in radius lengths)
        - compactness (perimeter^2 / area - 1.0)
        - concavity (severity of concave portions of the contour)
        - concave points (number of concave portions of the contour)
        - symmetry
        - fractal dimension ("coastline approximation" - 1)

        The mean, standard error, and "worst" or largest (mean of the three
        worst/largest values) of these features were computed for each image,
        resulting in 30 features.  For instance, field 0 is Mean Radius, field
        10 is Radius SE, field 20 is Worst Radius.

        - class:
                - WDBC-Malignant
                - WDBC-Benign

    :Summary Statistics:

    ===================================== ====== ======
                                           Min    Max
    ===================================== ====== ======
    radius (mean):                        6.981  28.11
    texture (mean):                       9.71   39.28
    perimeter (mean):                     43.79  188.5
    area (mean):                          143.5  2501.0
    smoothness (mean):                    0.053  0.163
    compactness (mean):                   0.019  0.345
    concavity (mean):                     0.0    0.427
    concave points (mean):                0.0    0.201
    symmetry (mean):                      0.106  0.304
    fractal dimension (mean):             0.05   0.097
    radius (standard error):              0.112  2.873
    texture (standard error):             0.36   4.885
    perimeter (standard error):           0.757  21.98
    area (standard error):                6.802  542.2
    smoothness (standard error):          0.002  0.031
    compactness (standard error):         0.002  0.135
    concavity (standard error):           0.0    0.396
    concave points (standard error):      0.0    0.053
    symmetry (standard error):            0.008  0.079
    fractal dimension (standard error):   0.001  0.03
    radius (worst):                       7.93   36.04
    texture (worst):                      12.02  49.54
    perimeter (worst):                    50.41  251.2
    area (worst):                         185.2  4254.0
    smoothness (worst):                   0.071  0.223
    compactness (worst):                  0.027  1.058
    concavity (worst):                    0.0    1.252
    concave points (worst):               0.0    0.291
    symmetry (worst):                     0.156  0.664
    fractal dimension (worst):            0.055  0.208
    ===================================== ====== ======

    :Missing Attribute Values: None

    :Class Distribution: 212 - Malignant, 357 - Benign

    :Creator:  Dr. William H. Wolberg, W. Nick Street, Olvi L. Mangasarian

    :Donor: Nick Street

    :Date: November, 1995

This is a copy of UCI ML Breast Cancer Wisconsin (Diagnostic) datasets.
https://goo.gl/U2Uwz2

Features are computed from a digitized image of a fine needle
aspirate (FNA) of a breast mass.  They describe
characteristics of the cell nuclei present in the image.

Separating plane described above was obtained using
Multisurface Method-Tree (MSM-T) [K. P. Bennett, "Decision Tree
Construction Via Linear Programming." Proceedings of the 4th
Midwest Artificial Intelligence and Cognitive Science Society,
pp. 97-101, 1992], a classification method which uses linear
programming to construct a decision tree.  Relevant features
were selected using an exhaustive search in the space of 1-4
features and 1-3 separating planes.

The actual linear program used to obtain the separating plane
in the 3-dimensional space is that described in:
[K. P. Bennett and O. L. Mangasarian: "Robust Linear
Programming Discrimination of Two Linearly Inseparable Sets",
Optimization Methods and Software 1, 1992, 23-34].

This database is also available through the UW CS ftp server:

ftp ftp.cs.wisc.edu
cd math-prog/cpo-dataset/machine-learn/WDBC/

.. topic:: References

   - W.N. Street, W.H. Wolberg and O.L. Mangasarian. Nuclear feature extraction 
     for breast tumor diagnosis. IS&T/SPIE 1993 International Symposium on 
     Electronic Imaging: Science and Technology, volume 1905, pages 861-870,
     San Jose, CA, 1993.
   - O.L. Mangasarian, W.N. Street and W.H. Wolberg. Breast cancer diagnosis and 
     prognosis via linear programming. Operations Research, 43(4), pages 570-577, 
     July-August 1995.
   - W.H. Wolberg, W.N. Street, and O.L. Mangasarian. Machine learning techniques
     to diagnose breast cancer from fine-needle aspirates. Cancer Letters 77 (1994) 
     163-171.
data = cancer['data']
target = cancer['target']
feature_names=cancer['feature_names']
df = pd.DataFrame(data=data, columns=feature_names)
df['target'] = cancer['target']
df.head()
mean radius mean texture mean perimeter mean area mean smoothness mean compactness mean concavity mean concave points mean symmetry mean fractal dimension ... worst texture worst perimeter worst area worst smoothness worst compactness worst concavity worst concave points worst symmetry worst fractal dimension target
0 17.99 10.38 122.80 1001.0 0.11840 0.27760 0.3001 0.14710 0.2419 0.07871 ... 17.33 184.60 2019.0 0.1622 0.6656 0.7119 0.2654 0.4601 0.11890 0
1 20.57 17.77 132.90 1326.0 0.08474 0.07864 0.0869 0.07017 0.1812 0.05667 ... 23.41 158.80 1956.0 0.1238 0.1866 0.2416 0.1860 0.2750 0.08902 0
2 19.69 21.25 130.00 1203.0 0.10960 0.15990 0.1974 0.12790 0.2069 0.05999 ... 25.53 152.50 1709.0 0.1444 0.4245 0.4504 0.2430 0.3613 0.08758 0
3 11.42 20.38 77.58 386.1 0.14250 0.28390 0.2414 0.10520 0.2597 0.09744 ... 26.50 98.87 567.7 0.2098 0.8663 0.6869 0.2575 0.6638 0.17300 0
4 20.29 14.34 135.10 1297.0 0.10030 0.13280 0.1980 0.10430 0.1809 0.05883 ... 16.67 152.20 1575.0 0.1374 0.2050 0.4000 0.1625 0.2364 0.07678 0

5 rows × 31 columns

pos = df.loc[df['target']==1]
neg = df.loc[df['target']==0]
pos
mean radius mean texture mean perimeter mean area mean smoothness mean compactness mean concavity mean concave points mean symmetry mean fractal dimension ... worst texture worst perimeter worst area worst smoothness worst compactness worst concavity worst concave points worst symmetry worst fractal dimension target
19 13.540 14.36 87.46 566.3 0.09779 0.08129 0.06664 0.047810 0.1885 0.05766 ... 19.26 99.70 711.2 0.14400 0.17730 0.23900 0.12880 0.2977 0.07259 1
20 13.080 15.71 85.63 520.0 0.10750 0.12700 0.04568 0.031100 0.1967 0.06811 ... 20.49 96.09 630.5 0.13120 0.27760 0.18900 0.07283 0.3184 0.08183 1
21 9.504 12.44 60.34 273.9 0.10240 0.06492 0.02956 0.020760 0.1815 0.06905 ... 15.66 65.13 314.9 0.13240 0.11480 0.08867 0.06227 0.2450 0.07773 1
37 13.030 18.42 82.61 523.8 0.08983 0.03766 0.02562 0.029230 0.1467 0.05863 ... 22.81 84.46 545.9 0.09701 0.04619 0.04833 0.05013 0.1987 0.06169 1
46 8.196 16.84 51.71 201.9 0.08600 0.05943 0.01588 0.005917 0.1769 0.06503 ... 21.96 57.26 242.2 0.12970 0.13570 0.06880 0.02564 0.3105 0.07409 1
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
558 14.590 22.68 96.39 657.1 0.08473 0.13300 0.10290 0.037360 0.1454 0.06147 ... 27.27 105.90 733.5 0.10260 0.31710 0.36620 0.11050 0.2258 0.08004 1
559 11.510 23.93 74.52 403.5 0.09261 0.10210 0.11120 0.041050 0.1388 0.06570 ... 37.16 82.28 474.2 0.12980 0.25170 0.36300 0.09653 0.2112 0.08732 1
560 14.050 27.15 91.38 600.4 0.09929 0.11260 0.04462 0.043040 0.1537 0.06171 ... 33.17 100.20 706.7 0.12410 0.22640 0.13260 0.10480 0.2250 0.08321 1
561 11.200 29.37 70.67 386.0 0.07449 0.03558 0.00000 0.000000 0.1060 0.05502 ... 38.30 75.19 439.6 0.09267 0.05494 0.00000 0.00000 0.1566 0.05905 1
568 7.760 24.54 47.92 181.0 0.05263 0.04362 0.00000 0.000000 0.1587 0.05884 ... 30.37 59.16 268.6 0.08996 0.06444 0.00000 0.00000 0.2871 0.07039 1

357 rows × 31 columns

sample = pd.concat([pos, neg[:5]], sort = True)
x_train, x_test, y_train, y_test = train_test_split(sample.drop('target', 1), sample['target'], random_state = 42 )
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(x_train, y_train)
pred = model.predict(x_test)
(pred == y_test).mean()
0.978021978021978
my_prediction = np.ones(shape=y_test.shape)
(my_prediction == y_test).mean()
0.989010989010989

Confusion matrix

from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
confusion_matrix(y_test, pred)
array([[ 1,  0],
       [ 2, 88]], dtype=int64)
sns.heatmap(confusion_matrix(y_test, pred), annot = True, cmap = 'Reds')
plt.xlabel('Predict')
plt.ylabel('Actual')
plt.show()

# soruce: https://dojinkimm.github.io
Image('https://dojinkimm.github.io/assets/imgs/ml/handson_3_1.png', width=500)

from sklearn.metrics import precision_score, recall_score

Precision

Positive Prediction Accuracy

TP / (TP + FP)

precision_score(y_test, pred)
1.0

It’s not useful because you get good precision if you judge it unconditionally as positive.

Recall

TP / (TP + FN)

Proportion of positive samples correctly detected.

Also called sensitivity or True Positive Rate (TPR).

recall_score(y_test, pred)
0.9777777777777777
88/90
0.9777777777777777

F1 score

\[2*\frac{precision * recall}{precision + recall}=\frac{TP}{TP+\frac{FN+FP}{2}}\]
from sklearn.metrics import f1_score
f1_score(y_test, pred)
0.9887640449438202

댓글남기기