Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Trong mã của bạn, bạn đang tạo ra một bài kiểm tra đào tạo tĩnh. Nếu bạn muốn chọn độ sâu tốt nhất bằng cách xác thực chéo, bạn có thể sử dụng

# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset
1 bên trong vòng lặp cho.

Bạn có thể đọc tài liệu của Sklearn để biết thêm thông tin.

Dưới đây là bản cập nhật mã của bạn với CV:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.cross_validation import cross_val_score
from pprint import pprint

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']

# x_train,x_test,y_train,y_test = cross_validation.train_test_split(x,y,test_size=0.4,random_state=0)
depth = []
for i in range(3,20):
    clf = tree.DecisionTreeClassifier(max_depth=i)
    # Perform 7-fold cross validation 
    scores = cross_val_score(estimator=clf, X=x, y=y, cv=7, n_jobs=4)
    depth.append((i,scores.mean()))
print(depth)

Ngoài ra, bạn có thể sử dụng

# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset
2 và không tự viết vòng lặp, đặc biệt nếu bạn muốn tối ưu hóa cho nhiều hơn một tham số siêu.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 

Chỉnh sửa: Đã thay đổi cách nhập gridSearchCV để đáp ứng nhận xét của Learn2Day. changed how GridSearchCV is imported to accommodate learn2day's comment.

Chiến lược điển hình nhất trong học máy là chia một tập dữ liệu thành tập huấn luyện và xác nhận. 70:30 hoặc 80:20 có thể là tỷ lệ phân chia. Đó là phương pháp nắm giữ.

Vấn đề với chiến lược này là chúng tôi không biết nếu độ chính xác xác thực cao cho thấy một mô hình tốt. Điều gì sẽ xảy ra nếu phần dữ liệu chúng tôi sử dụng để xác thực hóa ra là một thành công? Mô hình của chúng tôi sẽ vẫn chính xác nếu chúng tôi sử dụng một phần khác của tập dữ liệu làm bộ xác thực? Đây là một số câu hỏi mà K-Fold CV trả lời.

Điều kiện tiên quyết

Để làm theo với hướng dẫn này, bạn cần phải có:

  • Bộ dữ liệu ung thư vú Wisconsin. Bạn có thể tìm thấy nó ở đây.
  • Google colaboratory hoặc Jupyter Notebook.

Đề cương

  • Giới thiệu
  • Tiền xử lý dữ liệu
  • Xác thực chéo 5 lần
  • Đào tạo mô hình
  • Sự kết luận
  • Người giới thiệu

Giới thiệu

Tiền xử lý dữ liệu

Xác thực chéo 5 lần

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Đào tạo mô hình

Xử lý chéo K-Fold là một kỹ thuật vượt trội để xác nhận hiệu suất của mô hình của chúng tôi. Nó đánh giá mô hình bằng cách sử dụng các khối khác nhau của tập dữ liệu làm tập xác thực.

Chúng tôi chia tập dữ liệu của chúng tôi thành K-Fold. K đại diện cho số lượng nếp gấp mà bạn muốn phân chia dữ liệu của mình. Nếu chúng ta sử dụng 5 lần, tập dữ liệu chia thành năm phần. Trong các lần lặp khác nhau, một phần trở thành bộ xác thực.

Nguồn hình ảnh: Blog học tập tuyệt vời

# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Trong lần lặp đầu tiên, chúng tôi sử dụng phần đầu tiên của dữ liệu để xác thực. Như được minh họa trong hình trên, chúng tôi sử dụng các phần khác của tập dữ liệu để đào tạo.

# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')

Output:

    Matrix of features
    [[1.799e+01 1.038e+01 1.228e+02 ... 2.654e-01 4.601e-01 1.189e-01]
     [2.057e+01 1.777e+01 1.329e+02 ... 1.860e-01 2.750e-01 8.902e-02]
     [1.969e+01 2.125e+01 1.300e+02 ... 2.430e-01 3.613e-01 8.758e-02]
     ...
     [1.660e+01 2.808e+01 1.083e+02 ... 1.418e-01 2.218e-01 7.820e-02]
     [2.060e+01 2.933e+01 1.401e+02 ... 2.650e-01 4.087e-01 1.240e-01]
     [7.760e+00 2.454e+01 4.792e+01 ... 0.000e+00 2.871e-01 7.039e-02]]
    --------------------------------------------------
    Target Variable
    ['M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M'
     'M' 'B' 'B' 'B' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M'
     'M' 'B' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M'
     'M' 'B' 'M' 'M' 'B' 'B' 'B' 'B' 'M' 'B' 'M' 'M' 'B' 'B' 'B' 'B' 'M' 'B'
     'M' 'M' 'B' 'M' 'B' 'M' 'M' 'B' 'B' 'B' 'M' 'M' 'B' 'M' 'M' 'M' 'B' 'B'
     'B' 'M' 'B' 'B' 'M' 'M' 'B' 'B' 'B' 'M' 'M' 'B' 'B' 'B' 'B' 'M' 'B' 'B'
     'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'M' 'M' 'B' 'M' 'M' 'B' 'B' 'B'
     'M' 'M' 'B' 'M' 'B' 'M' 'M' 'B' 'M' 'M' 'B' 'B' 'M' 'B' 'B' 'M' 'B' 'B'
     'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'M'
     'M' 'B' 'M' 'B' 'B' 'M' 'M' 'B' 'B' 'M' 'M' 'B' 'B' 'B' 'B' 'M' 'B' 'B'
     'M' 'M' 'M' 'B' 'M' 'B' 'M' 'B' 'B' 'B' 'M' 'B' 'B' 'M' 'M' 'B' 'M' 'M'
     'M' 'M' 'B' 'M' 'M' 'M' 'B' 'M' 'B' 'M' 'B' 'B' 'M' 'B' 'M' 'M' 'M' 'M'
     'B' 'B' 'M' 'M' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M' 'M' 'B' 'B' 'M'
     'B' 'B' 'M' 'M' 'B' 'M' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M' 'B'
     'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'M' 'B' 'B' 'B' 'B'
     'B' 'B' 'M' 'B' 'M' 'B' 'B' 'M' 'B' 'B' 'M' 'B' 'M' 'M' 'B' 'B' 'B' 'B'
     'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'M' 'B' 'M' 'B' 'B' 'B'
     'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'M' 'B' 'M'
     'B' 'B' 'B' 'B' 'M' 'M' 'M' 'B' 'B' 'B' 'B' 'M' 'B' 'M' 'B' 'M' 'B' 'B'
     'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'M' 'M' 'B' 'B' 'B' 'B' 'B' 'B'
     'B' 'B' 'B' 'B' 'B' 'M' 'M' 'B' 'M' 'M' 'M' 'B' 'M' 'M' 'B' 'B' 'B' 'B'
     'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'M' 'B' 'B' 'M' 'M' 'B' 'B'
     'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B'
     'M' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B'
     'M' 'M' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'M' 'B' 'M' 'B' 'B' 'M'
     'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'M' 'B' 'B' 'B' 'B' 'B' 'B'
     'M' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'B'
     'B' 'M' 'B' 'M' 'B' 'B' 'M' 'B' 'B' 'B' 'B' 'B' 'M' 'M' 'B' 'M' 'B' 'M'
     'B' 'B' 'B' 'B' 'B' 'M' 'B' 'B' 'M' 'B' 'M' 'B' 'M' 'M' 'B' 'B' 'B' 'M'
     'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'M' 'B' 'M' 'M' 'B' 'B' 'B'
     'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B'
     'B' 'B' 'B' 'B' 'M' 'M' 'M' 'M' 'M' 'M' 'B']

Tiền xử lý dữ liệu

# Label Encode the target variable
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
encoded_y = label_encoder.fit_transform(y)
label_encoder_name_mapping = dict(zip(label_encoder.classes_,
                                         label_encoder.transform(label_encoder.classes_)))
print("Mapping of Label Encoded Classes", label_encoder_name_mapping, sep="\n")
print("Label Encoded Target Variable", encoded_y, sep="\n")

Output:

    Mapping of Label Encoded Classes
    {'B': 0, 'M': 1}
    Label Encoded Target Variable
    [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
     0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 0 1 0 1 1
     0 1 0 1 1 0 0 0 1 1 0 1 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0 0 0 0 1 0 0 1 0 0
     0 0 0 0 0 0 1 1 1 0 1 1 0 0 0 1 1 0 1 0 1 1 0 1 1 0 0 1 0 0 1 0 0 0 0 1 0
     0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 0 0 0 1 0 0 1 1 1 0 1
     0 1 0 0 0 1 0 0 1 1 0 1 1 1 1 0 1 1 1 0 1 0 1 0 0 1 0 1 1 1 1 0 0 1 1 0 0
     0 1 0 0 0 0 0 1 1 0 0 1 0 0 1 1 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 1 1 1 1 1 1
     1 1 1 1 1 1 1 0 0 0 0 0 0 1 0 1 0 0 1 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0
     0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 1 1 1 0 0
     0 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1
     1 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0
     0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0
     1 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0
     0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 1 1
     0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 1 1 1 1 1 1 0]

Chúng tôi nhập tất cả các thư viện có liên quan cho dự án và tải tập dữ liệu.

Biến mục tiêu là cột chẩn đoán. Nó có chỉ số 1. Các tính năng là tất cả các cột ngoại trừ ID, chẩn đoán và không tên: 32 cột.

Biến mục tiêu chứa chuỗi, chúng ta phải thay đổi chuỗi thành số.

# K-Fold Cross-Validation
from sklearn.model_selection import cross_validate
def cross_validation(model, _X, _y, _cv=5):
      '''Function to perform 5 Folds Cross-Validation
       Parameters
       ----------
      model: Python Class, default=None
              This is the machine learning algorithm to be used for training.
      _X: array
           This is the matrix of features.
      _y: array
           This is the target variable.
      _cv: int, default=5
          Determines the number of folds for cross-validation.
       Returns
       -------
       The function returns a dictionary containing the metrics 'accuracy', 'precision',
       'recall', 'f1' for both training set and validation set.
      '''
      _scoring = ['accuracy', 'precision', 'recall', 'f1']
      results = cross_validate(estimator=model,
                               X=_X,
                               y=_y,
                               cv=_cv,
                               scoring=_scoring,
                               return_train_score=True)
      
      return {"Training Accuracy scores": results['train_accuracy'],
              "Mean Training Accuracy": results['train_accuracy'].mean()*100,
              "Training Precision scores": results['train_precision'],
              "Mean Training Precision": results['train_precision'].mean(),
              "Training Recall scores": results['train_recall'],
              "Mean Training Recall": results['train_recall'].mean(),
              "Training F1 scores": results['train_f1'],
              "Mean Training F1 Score": results['train_f1'].mean(),
              "Validation Accuracy scores": results['test_accuracy'],
              "Mean Validation Accuracy": results['test_accuracy'].mean()*100,
              "Validation Precision scores": results['test_precision'],
              "Mean Validation Precision": results['test_precision'].mean(),
              "Validation Recall scores": results['test_recall'],
              "Mean Validation Recall": results['test_recall'].mean(),
              "Validation F1 scores": results['test_f1'],
              "Mean Validation F1 Score": results['test_f1'].mean()
              }

Số 0 đại diện cho Benign, trong khi 1 đại diện cho ác tính.

Xác thực chéo 5 lần

Chúng tôi sử dụng chức năng

# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset
3 từ mô-đun thư viện Scikit-learn ____ ____24.

Chúng tôi tạo ra một chức năng để trực quan hóa kết quả đào tạo và xác nhận trong mỗi lần. Hàm sẽ hiển thị một biểu đồ thanh được nhóm.

# Grouped Bar Chart for both training and validation data
def plot_result(x_label, y_label, plot_title, train_data, val_data):
        '''Function to plot a grouped bar chart showing the training and validation
          results of the ML model in each fold after applying K-fold cross-validation.
         Parameters
         ----------
         x_label: str, 
            Name of the algorithm used for training e.g 'Decision Tree'
          
         y_label: str, 
            Name of metric being visualized e.g 'Accuracy'
         plot_title: str, 
            This is the title of the plot e.g 'Accuracy Plot'
         
         train_result: list, array
            This is the list containing either training precision, accuracy, or f1 score.
        
         val_result: list, array
            This is the list containing either validation precision, accuracy, or f1 score.
         Returns
         -------
         The function returns a Grouped Barchart showing the training and validation result
         in each fold.
        '''
        
        # Set size of plot
        plt.figure(figsize=(12,6))
        labels = ["1st Fold", "2nd Fold", "3rd Fold", "4th Fold", "5th Fold"]
        X_axis = np.arange(len(labels))
        ax = plt.gca()
        plt.ylim(0.40000, 1)
        plt.bar(X_axis-0.2, train_data, 0.4, color='blue', label='Training')
        plt.bar(X_axis+0.2, val_data, 0.4, color='red', label='Validation')
        plt.title(plot_title, fontsize=30)
        plt.xticks(X_axis, labels)
        plt.xlabel(x_label, fontsize=14)
        plt.ylabel(y_label, fontsize=14)
        plt.legend()
        plt.grid(True)
        plt.show()

Đào tạo mô hình

Bây giờ chúng tôi có thể đào tạo thuật toán học máy của chúng tôi. Chúng tôi sẽ sử dụng thuật toán cây quyết định. Chúng tôi nhập

# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')
3 từ mô -đun
# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')
4 của thư viện
# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')
5. Chúng tôi cũng gọi chức năng
# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset
5 mà chúng tôi đã tạo trước đó để thực hiện xác thực chéo 5 lần.

from sklearn.tree import DecisionTreeClassifier
decision_tree_model = DecisionTreeClassifier(criterion="entropy",
                                     random_state=0)
decision_tree_result = cross_validation(decision_tree_model, X, encoded_y, 5)
print(decision_tree_result)

Output:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
0

Để hiểu kết quả tốt hơn, chúng ta có thể hình dung chúng. Chúng tôi sử dụng chức năng

# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')
7 mà chúng tôi đã tạo trước đó. Chúng tôi bắt đầu bằng cách hình dung độ chính xác của đào tạo và độ chính xác xác nhận trong mỗi lần.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
1

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Chúng ta cũng có thể hình dung độ chính xác đào tạo và độ chính xác xác nhận trong mỗi lần.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
2

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Hãy để chúng tôi hình dung việc thu hồi đào tạo và thu hồi xác nhận trong mỗi lần.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
3

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Cuối cùng, chúng tôi hình dung điểm F1 và điểm xác thực F1 trong mỗi lần.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
4

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Các trực quan hóa cho thấy độ chính xác đào tạo, độ chính xác, thu hồi và điểm F1 trong mỗi lần là 100%. Nhưng độ chính xác xác nhận, độ chính xác, thu hồi và điểm F1 không cao. Chúng tôi gọi đây là sự phù hợp quá mức. Mô hình thực hiện đáng ngưỡng mộ trên dữ liệu đào tạo. Nhưng không quá nhiều trên bộ xác nhận.

Hình dung kết quả của bạn như thế này có thể giúp bạn xem liệu mô hình của bạn có phù hợp quá mức hay không. Chúng tôi điều chỉnh các tham số siêu ____38 trong thuật toán cây quyết định. Nó sẽ khắc phục vấn đề quá mức. Giá trị mặc định của tham số

# Separate features and target variable
X = dataset.iloc[:, 2:-1].values
y = dataset. iloc [:, 1].values
print("Matrix of features", X, sep='\n')
print("--------------------------------------------------")
print("Target Variable", y, sep='\n')
8 là 2. Chúng tôi tăng giá trị lên 5.

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
5

Output:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
6

Hãy để chúng tôi hình dung kết quả của mô hình thứ hai.

Độ chính xác của đào tạo và độ chính xác xác nhận trong mỗi lần:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
7

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Độ chính xác và xác nhận độ chính xác xác nhận trong mỗi lần:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
8

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Việc thu hồi và thu hồi xác nhận đào tạo trong mỗi lần:

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.model_selection import GridSearchCV

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)
df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']


parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
clf.fit(X=x, y=y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
9

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Điểm F1 và Xác thực F1 trong mỗi lần:

# import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
%matplotlib inline

# load dataset
dataset = pd.read_csv('breast_cancer_data.csv')
dataset
0

Hướng dẫn cross validation decision tree python - xác thực chéo cây quyết định python

Chúng ta có thể thấy rằng kết quả xác thực của mô hình thứ hai trong mỗi nếp gấp tốt hơn. Nó có độ chính xác xác thực trung bình là 93,85% và điểm F1 xác thực trung bình là 91,69%. Bạn có thể tìm thấy repo GitHub cho dự án này ở đây.

Sự kết luận

Khi đào tạo một mô hình trên một bộ dữ liệu nhỏ, kỹ thuật xác thực chéo K có ích. Bạn có thể không cần sử dụng xác thực chéo K-gấp K nếu việc thu thập dữ liệu của bạn rất lớn. Lý do là bạn có đủ hồ sơ trong bộ xác thực của mình để kiểm tra mô hình học máy. Phải mất rất nhiều thời gian để sử dụng xác thực chéo K trên một bộ sưu tập dữ liệu lớn.

Cuối cùng, sử dụng nhiều nếp gấp để kiểm tra mô hình của bạn tiêu thụ nhiều tài nguyên điện toán hơn. Giá trị của K càng cao, càng mất nhiều thời gian để đào tạo mô hình. Nếu K = 5, mô hình đào tạo năm lần bằng năm nếp gấp khác nhau làm bộ xác thực. Nếu k = 10, mô hình đào tạo mười lần.

Người giới thiệu

  1. https://stats.stackexchange.com/questions/52274/how-to-choose-a-predictive-model-after-k-fold-cross-validation
  2. Blog học tập tuyệt vời

Đóng góp đánh giá ngang hàng của: Wilkister Mumbi

Bạn có thể sử dụng chéo

Xác thực chéo được sử dụng trong một loạt các phương pháp học máy, chẳng hạn như học tập dựa trên trường hợp, mạng lưới thần kinh nhân tạo hoặc cảm ứng cây quyết định..

Cross là gì

Có thể sử dụng xác thực cây chéo để giảm tỷ lệ lỗi của mô hình cây phân loại 'cắt tỉa'. Đây là một kỹ thuật xác thực chéo cung cấp kích thước của cây và độ lệch hoặc lỗi tương ứng. Sử dụng kích thước có độ lệch thấp nhất, chúng ta có thể xây dựng mô hình cây cho kích thước đó và cải thiện độ chính xác.a cross-validation technique which gives the size of tree and the corresponding deviance or error. Using the size that has the lowest deviance we can build the tree model for that size and improve accuracy.

Làm cách nào để sử dụng chéo

Có nhiều phương pháp để xác nhận chéo, chúng tôi sẽ bắt đầu bằng cách nhìn vào xác thực chéo K gấp K ...
K-gấp.Dữ liệu đào tạo được sử dụng trong mô hình được chia, thành số k của các bộ nhỏ hơn, được sử dụng để xác nhận mô hình.....
Phân tầng K-Fold.....
Rời khỏi một (loo) ....
Rời khỏi-p-out (LPO) ....
Shuffle Split ..

Làm thế nào để bạn kiểm tra độ chính xác của cây quyết định trong Python?

Bạn nên thực hiện xác thực chéo nếu bạn muốn kiểm tra độ chính xác của hệ thống.Bạn phải chia cho bạn tập dữ liệu thành hai phần.Cái đầu tiên được sử dụng để tìm hiểu hệ thống của bạn.Sau đó, bạn thực hiện quy trình dự đoán trên phần thứ hai của tập dữ liệu và so sánh các kết quả dự đoán với các kết quả tốt.perform a cross validation if you want to check the accuracy of your system. You have to split you data set into two parts. The first one is used to learn your system. Then you perform the prediction process on the second part of the data set and compared the predicted results with the good ones.