Practical data analysis | Logistic regression – automatic diagnosis and analysis of cases

Table of Contents

1. Data and analysis objects

2. Purpose and analysis tasks

3. Methods and Tools

4. Data reading

5. Data understanding

6. Data preparation

7. Model training

8. Model evaluation

9. Model parameter adjustment

10. Model prediction


1. Data and analysis objects

CSV file – “bc_data.csv”

Dataset link: https://download.csdn.net/download/m0_70452407/88524905

This data set mainly records 32 attributes of 569 cases. The main attributes/fields are as follows:

(1) ID: ID of the case.

(2) Diagnosis: M means malignant, B means benign. This dataset contains a total of 357 benign cases and 212 malignant cases.

(3) 10 characteristic values of the cell nucleus, including radius, texture, perimeter, area, smoothness, compactness, concavity, concavity Points (concave points), symmetry (symmetry) and fractal dimension (fractal dimension), etc. At the same time, three statistics are provided for the above 10 eigenvalues, namely mean, standard error and worst or largest.

2. Purpose and Analysis Tasks

Understand the application of machine learning methods in data analysis – using logistic regression methods for classification analysis.

(1) Data reading.

(2) Divide the training set and data set, and use the logistic regression algorithm for model training and classification analysis.

(3) Carry out model evaluation and adjust model parameters.

(4) Perform model prediction on the adjusted model, and compare and analyze the results with the test set results to verify the effectiveness of the logistic regression algorithm modeling.

3. Methods and Tools

Python language and scikit-learn package.

4. Data reading

Import the required toolkits:

import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import metrics

Import the data set that comes with scikit-learn – the Wisconsin breast cancer data set. The implementation method used here is to call the load_breast_cancer() method in sklearn.datasets.

#Data reading
from sklearn.datasets import load_breast_cancer
breast_cancer=load_breast_cancer()

The imported Wisconsin breast cancer data set is dictionary data, and the keys to display its dictionary are:

#Display the keys of the data set dictionary
print(breast_cancer.keys())
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', ' data_module'])

In the output result, ‘target’ is the classification target, ‘DESCR’ is the complete description of the data set, and ‘feature_names’ is the feature name.

Show the full description of the dataset:

print(breast_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.

Display the feature names of the dataset:

#Feature name of the data set
print(breast_cancer.feature_names)
['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']

Show data shape:

#Data shape
print(breast_cancer.data.shape)
(569, 30)

Call the pandas package data frame (DataFrame) to convert the data (data) and regression target (target) into data frame types.

#Convert data and regression target to data frame type
X=pd.DataFrame(breast_cancer.data,columns=breast_cancer.feature_names)
y=pd.DataFrame(breast_cancer.target,columns=['class'])

After merging the X and y data frames, the data set df is generated

#Merge data frames
df=pd.concat([X,y],axis=1)
df

5. Data Understanding

View basic information about the data:

#View basic information of data
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 569 entries, 0 to 568
Data columns (total 31 columns):
 # Column Non-Null Count Dtype
--- ------ -------------- -----
 0 mean radius 569 non-null float64
 1 mean texture 569 non-null float64
 2 mean perimeter 569 non-null float64
 3 mean area 569 non-null float64
 4 mean smoothness 569 non-null float64
 5 mean compactness 569 non-null float64
 6 mean concavity 569 non-null float64
 7 mean concave points 569 non-null float64
 8 mean symmetry 569 non-null float64
 9 mean fractal dimension 569 non-null float64
 10 radius error 569 non-null float64
 11 texture error 569 non-null float64
 12 perimeter error 569 non-null float64
 13 area error 569 non-null float64
 14 smoothness error 569 non-null float64
 15 compactness error 569 non-null float64
 16 concavity error 569 non-null float64
 17 concave points error 569 non-null float64
 18 symmetry error 569 non-null float64
 19 fractal dimension error 569 non-null float64
 20 worst radius 569 non-null float64
 21 worst texture 569 non-null float64
 22 worst perimeter 569 non-null float64
 23 worst area 569 non-null float64
 24 worst smoothness 569 non-null float64
 25 worst compactness 569 non-null float64
 26 worst concavity 569 non-null float64
 27 worst concave points 569 non-null float64
 28 worst symmetry 569 non-null float64
 29 worst fractal dimension 569 non-null float64
 30 class 569 non-null int32
dtypes: float64(30), int32(1)
memory usage: 135.7 KB

View descriptive statistics:

#View description of new statistical information
df.describe()

6. Data preparation

Use the train_test_split() method of sklearn.model_selection to divide the training set and the test set, fix random_state to 42, use 30% of the data for testing, and 70% of the data for training.

#Divide training set and test set
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,
                                               test_size=0.3,random_state=42)
X_test

Seven. Model Training

Call LogisticRegression with default parameters to train the model on the training set.

#Model training
model=LogisticRegression(C=1.0,
                         class_weight=None,
                         dual=False,
                         fit_intercept=True,
                         intercept_scaling=1,
                         max_iter=100,
                         multi_class='ovr',
                         n_jobs=1,
                         penalty='l2',
                         random_state=None,
                         solver='liblinear',
                         tol=0.0001,
                         verbose=0,
                         warm_start=False)
model.fit(X_train,y_train)
LogisticRegression(multi_class='ovr', n_jobs=1, solver='liblinear')

This output shows the training results of the model. Select default values for logistic regression model parameters for training. Select the L2 regularization term, and C=1.0 controls the strength of regularization. “fit_intercept=True,intercept_scaling=1” means increasing intercept scaling and reducing the impact of regularization on comprehensive feature weights. “class_weight=None” means that all classes have weights. When “solver=liblinear” (use “liblinear” algorithm when optimizing problems). max_iter=100 means that the maximum number of iterations used by the solver to converge is 100. multi_class=”ovr” means that each label fits a binary problem. n_jobs represents the number of CPU cores used when parallelizing the class. When warm_start is set to True, the solution from the previous call is reused to accommodate initialization, otherwise, the previous solution is simply deleted.

Show prediction results:

#Default parameter model prediction result y_pred
y_pred=model.predict(X_test)
y_pred
array([1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1,
       0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1,
       1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1,
       0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0,
       1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1,
       0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0,
       1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
       1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1])

8. Model Evaluation

Use the indicators of the confusion matrix classification algorithm to evaluate the classification effect of the model.

#Confusion matrix (an important evaluation indicator for classification algorithms)
matrix=metrics.confusion_matrix(y_test,y_pred)
matrix
array([[ 59, 4],
       [ 2, 106]], dtype=int64)

The two classification indicators of Accuracy and Precision are used to evaluate the classification effect of the model.

#Classification evaluation index - accuracy (Accuracy)
print("Accuracy:",metrics.accuracy_score(y_test,y_pred))

#Classification evaluation index - precision (Precision)
print("Precision:",metrics.precision_score(y_test,y_pred))
Accuracy: 0.9649122807017544
Precision: 0.9636363636363636

9. Model parameter adjustment

Set the param_grid and cv parameter values of the GridSearchCV function. In order to prevent the occurrence of over-fitting, the degree of regularization is controlled by parameter C. The larger the C value, the weaker the regularization. In general, as C increases (the degree of regularization is weak), the accuracy of the model improves on both the training set and the test set (the penalty on the loss function weakens), there are more feature dimensions, stronger learning ability, and overfitting The risk is also higher. The two regularization terms L1 and L2 have different effects on the objective function, and the gradient descent method of the chosen solution model is also different.

#Set the dictionary list param_grid with C, penalty parameters and values.
#Set the cv parameter value to 5
param_grid={'C':[0.001,0.01,0.1,1,10,20,50,100],
            'penalty':["l1","l2"]}
n_folds=5

Call the GridSearchCV function to perform 5-fold cross validation to obtain the optimal parameters of the model:

#Call the GridSearchCV function to perform 5-fold cross-validation, conduct an exhaustive search for the specified parameter value param_grid of the estimator LogisticRegression(), and obtain the final optimal model parameters.
from sklearn.model_selection import GridSearchCV
estimator=GridSearchCV(LogisticRegression(solver='liblinear'),param_grid,cv=n_folds)
estimator.fit(X_train,y_train)
GridSearchCV(cv=5, estimator=LogisticRegression(solver='liblinear'),
             param_grid={'C': [0.001, 0.01, 0.1, 1, 10, 20, 50, 100],
                         'penalty': ['l1', 'l2']})

This output shows a call to the GridSearchCV() method to perform an exhaustive search for the specified parameter values of the estimator.

Using the best_estimator_ attribute, get the highest score (or least loss estimator) selected by the search:

estimator.best_estimator_
LogisticRegression(C=50, penalty='l1', solver='liblinear')

The output shows that the optimal model parameters are C=50, penalty=”l1″

10. Model Prediction

Model training after parameter adjustment:

#Model training after parameter adjustment
model1=LogisticRegression(C=50,
                         class_weight=None,
                         dual=False,
                         fit_intercept=True,
                         intercept_scaling=1,
                         max_iter=100,
                         multi_class='ovr',
                         n_jobs=1,
                         penalty='l1',
                         random_state=None,
                         solver='liblinear',
                         tol=0.0001,
                         verbose=0,
                         warm_start=False)
model1.fit(X_train,y_train)
LogisticRegression(C=50, multi_class='ovr', n_jobs=1, penalty='l1',
                   solver='liblinear')

Model prediction after parameter adjustment:

#Model prediction after parameter adjustment
y_pred1=model1.predict(X_test)
y_pred1
array([1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1,
       0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1,
       1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1,
       0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0,
       1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1,
       0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0,
       1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
       1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1])

Model confusion matrix result after parameter adjustment:

# Model confusion matrix results after parameter adjustment
matrix1=metrics.confusion_matrix(y_test,y_pred1)
matrix1
array([[ 62, 1],
       [ 3, 105]], dtype=int64)

Model accuracy and precision classification index evaluation results after parameter adjustment:

# Model accuracy and precision classification index evaluation results after parameter adjustment
print("Accuracy1:",metrics.accuracy_score(y_test,y_pred1))
print("Precision1:",metrics.precision_score(y_test,y_pred1))
Accuracy1: 0.9766081871345029
Precision1: 0.9905660377358491

The output shows the model classification index accuracy (Accuracy) and precision (Precision) classification index values after parameter adjustment. By comparing the classification effect with the previous model without adjusting parameters, it can be found that the accuracy (Accuracy) and precision (Precision) values are improved, the results obtained by the confusion matrix are also better, and the classification effect is significantly improved.