ویرگول
ورودثبت نام
محمدحسین ف
محمدحسین ف
محمدحسین ف
محمدحسین ف
خواندن ۳۲ دقیقه·۵ سال پیش

Cross-Validation

Cross-Validation in Machine Learning: How to Do It Right

اعتبار سنجی متقابل در یادگیری ماشین:چگونه می­توان آن را به درستی انجام داد

10 mins read

Author Vladimir Lysenko

Updated November 12th, 2021

نویسنده: ولادمیر لیاشنکو

In machine learning (ML), generalization usually refers to the ability of an algorithm to be effective across various inputs. It means that the ML model does not encounter performance degradation on the new inputs from the same distribution of the training data.

در یادگیری ماشین[1] (ML)، تعمیم[2]معمولاً به توانایی یک الگوریتم برای کارآمدبودن در ورودی های مختلف اشاره دارد. این بدان معنی است که مدل یادگیری ماشین با کاهش عملکرد در ورودی­های جدیدی که از توزیع یکسانی با داده­های آموزشی دارند مواجه نمی­شود.

For human beings’ generalization is the most natural thing possible. We can classify on the fly. For example, we would definitely recognize a dog even if we didn’t see this breed before. Nevertheless, it might be quite a challenge for an ML model. That’s why checking the algorithm’s ability to generalize is an important task that requires a lot of attention when building the model.

برای انسان تعمیم یکی از طبیعی ترین چیزهای ممکن است. ما می­تونیم رو هوا طبقه بندی کنیم. به عنوان مثال، ما قطعاً یک سگ را می­شناسیم حتی اگر قبلاً این نژاد را ندیده باشیم. با این وجود، ممکن است این کار برای یک مدل یادگیری ماشین کاملاً یک چالش باشد. به همین دلیل است که در ساخت مدل بررسی توانایی الگوریتم برای تعمیم یک کار مهم بوده و نیاز به توجه زیادی دارد.

To do that, we use Cross-Validation (CV).

برای این کار(تعمیم) ازروش اعتبار سنجی متقابل[3] (CV) استفاده می­شود.

In this article we will cover:

در این مقاله به موارد زیر پرداخته می­شود:

What is Cross-Validation: definition, purpose of use and techniques

Different CV techniques: hold-out, k-folds, Leave-one-out, Leave-p-out, Stratified k-folds, Repeated k-folds, Nested k-folds, Complete CV

How to use these techniques: sklearn

Cross-Validation in Machine Learning: sklearn, Cat Boost

Cross-Validation in Deep Learning: Kera’s, PyTorch, Mx Net

Best practices and tips: time series, medical and financial data, images

· اعتبار سنجی متقابل چیست: تعریف، هدف استفاده و تکنیک ها

· تکنیک‌های مختلف: CV به روش برگزاری[4]، روش k-folds، اعتبار­سنجی یک طرفه[5]، اعتبار سنجی خارج از صفحه[6]، k-folds دسته­ای[7]، k-folds مکرر[8]، k-folds تودرتو[9]، روش اعتبارسنجی کامل[10]

· نحوه استفاده از این تکنیک ها sklearn:

· اعتبار سنجی متقابل در یادگیری ماشینی: sklearn، Cat Boost

· اعتبار سنجی متقابل در یادگیری عمیق: Kera’s، PyTorch، Mx Net

· بهترین برای شیوه­ها و کارهایی از جمله: سری های زمانی، داده های پزشکی و مالی، تصاویر

What is Cross-Validation

اعتبار سنجی متقابل چیست؟

Cross-validation is a technique for evaluating a machine learning model and testing its performance. CV is commonly used in applied ML tasks. It helps to compare and select an appropriate model for the specific predictive modeling problem.

اعتبارسنجی متقابل تکنیکی برای ارزیابی یک مدل یادگیری ماشینی و آزمایش عملکرد آن است. معمولاً در کارهای یادگیری ماشین استفاده می­شود که به مقایسه و انتخاب یک مدل متناسب با مسئله مدل‌سازی پیش‌بینی‌کننده مختص خود کمک می‌کند.

CV is easy to understand, easy to implement, and it tends to have a lower bias than other methods used to count the model’s efficiency scores. All this makes cross-validation a powerful tool for selecting the best model for the specific task.

درک و پیاده‌سازی CV آسان است، و مشکلات کمتری نسبت به سایر روش‌های مورد استفاده برای محاسبه کارایی مدل دارد. همه اینها اعتبار سنجی متقابل را به ابزاری قدرتمند برای انتخاب بهترین مدل برای کار های یادگیری ماشین تبدیل می­کند.

There are a lot of different techniques that may be used to cross-validate a model. Still, all of them have a similar algorithm:

تکنیک های مختلفی وجود دارد که ممکن است برای اعتبارسنجی متقابل یک مدل استفاده شود. با این حال، همه آنها یک الگوریتم مشابه دارند:

Divide the dataset into two parts: one for training, other for testing

Train the model on the training set

Validate the model on the test set

Repeat 1-3 steps a couple of times. This number depends on the CV method that you are using

1. مجموعه داده را به دو بخش تقسیم می­شود: یکی برای آموزش، دیگری برای تست

2. مدل را روی مجموعه آموزشی آموزش داده می­شود

3. اعتبار مدل را در مجموعه تست ارزیابی می­شود

ü مراحل 1 تا 3 چند بار تکرار می­شود. این تکرار به روش CVای که استفاده می­شود بستگی دارد.

As you may know, there are plenty of CV techniques. Some of them are commonly used, others work only in theory. Let’s see cross-validation methods that will be covered in this article.

با توجه با اینکه تکنیک­های CV زیادی وجود دارد. معمولا برخی از آنها استفاده می شوند، برخی دیگر تنها در حد فرضیه هستند. در این بخش روش­های اعتبار سنجی متقابل توضیح داده می­شود.

· روش برگزاری

· روش k-folds

· اعتبار­سنجی یک طرفه

· اعتبار سنجی خارج از صفحه

· k-folds دسته­ای

· k-folds مکرر

· k-folds تودرتو

· روش اعتبارسنجی کامل

Hold-out

K-folds

Leave-one-out

Leave-p-out

Stratified K-folds

Repeated K-folds

Nested K-folds

Complete

Hold-out

روش برگزاری

Hold-out cross-validation is the simplest and most common technique. You might not know that it is hold-out method but you certainly use it every day.

اعتبار سنجی متقابل به روش برگزاری ساده­ترین و رایج­ترین تکنیک است. ممکن است نحوه کار این روش را ندانید اما مطمئنا هر روز از آن استفاده می­کنید.

The algorithm of hold-out technique:

الگوریتم تکنیک برگزاری:

Hold out:

Divide the dataset into two parts: the training set and the test set. Usually, 80% of the dataset goes to the training set and 20% to the test set but you may choose any splitting that suits you better

Train the model on the training set

Validate on the test set

Save the result of the validation

1. مجموعه داده را به دو بخش تقسیم می­شود: مجموعه آموزشی و مجموعه تست. معمولاً 80 درصد مجموعه داده به مجموعه آموزشی و 20 درصد به مجموعه آزمایشی تقسیم می­شود، اما می‌توان هر تقسیم‌بندی را که مناسب­تر است را انتخاب کرد.

2. مدل بر روی مجموعه آموزشی، آموزش می­بیند.

3. در مجموعه تست ارزیابی می­شود.

4. نتیجه این ارزیابی ذخیره می­شود.

Hold-out cross-validation

اعتبارسنجی متقابل برگزاری

That’s it.

خودشه!

We usually use hold-out method on large datasets as it requires training the model only once.

از روش برگزاری در مجموعه داده‌های بزرگ استفاده می­شود، زیرا مدل فقط یک بار نیاز به آموزش دارد.

It is really easy to implement hold-out. For example, you may do it using sklearn. model _ selection . train _ test _split .

اجرای آن واقعاً آسان است. برای مثال، می‌توان این کار را با استفاده از sklearn.model_selection.train_test_split انجام داد.

import NumPy as np

from sklearn.model_selection import train_test_split

X, y = np. Arange (10. Reshape ((5, 2)), range (5)

X_train, X_test, y_train, y_test = train_test_split(X, y,

test_size=0.2,

random_state=111)

Still, hold-out has a major disadvantage.

با این حال، روش برگزاری یک نقطه ضعف بزرگ دارد.

For example, a dataset that is nor completely even distribution-wise. If so we may end up in a rough spot after the split. For example, the training set will not represent the test set. Both training and test sets may differ a lot, one of them might be easier or harder.

به عنوان مثال، مجموعه داده ای که در توزیع کاملاً یکنواخت نیست. اگر چنین باشد، ممکن است تقسیم داده­ها در یک نقطه نامناسب قرار گیرد. به عنوان مثال، مجموعه آموزشی، بیانگری از مجموعه تست نخواهد بود. هر دو مجموعه تمرین و تست ممکن است بسیار متفاوت باشند، یکی از آنها ممکن است آسان­تر یا سخت­تر باشد.

Moreover, the fact that we test our model only once might be a bottleneck for this method. Due to the reasons mentioned before, the result obtained by hold-out technique may be considered inaccurate.

علاوه بر این، این واقعیت که ما مدل خود را فقط یک بار آزمایش می کنیم ممکن است یک نقطه چالش برانگیز برای این روش باشد. با توجه به دلایلی که قبلا ذکر شد، نتیجه به دست آمده با تکنیک برگزاری ممکن است نادرست در نظر گرفته شود.

k-Fold CV is a technique that minimizes the disadvantages of hold-out method. k-Fold introduces a new way of splitting the dataset which helps to overcome the “test only once bottleneck”.

k-Fold

روش k-Fold تکنیکی است که معایب روش برگزاری را به حداقل می رساند. در این روش رویه جدیدی برای تقسیم مجموعه داده ارائه می­شود که به غلبه بر کشل 'فقط یک بار تست و نقطه چالش' کمک می­کند.

The algorithm of k-Fold technique:

الگوریتم تکنیک k-Fold:

Pick a number of folds – k. Usually, k is 5 or 10 but you can choose any number which is less than the dataset’s length.

Split the dataset into k equal (if possible) parts (they are called folds)

Choose k – 1 folds which will be the training set. The remaining fold will be the test set

Train the model on the training set. On each iteration of cross-validation, you must train a new model independently of the model trained on the previous iteration

Validate on the test set

Save the result of the validation

Repeat steps 3 – 6 k times. Each time use the remaining fold as the test set. In the end, you should have validated the model on every fold that you have.

To get the final score average the results that you got on step 6.

1. تعداد k برای اجرای این الگوریتم انتخاب می­شودکه معمولاً 5 یا 10 است، اما می‌توان هر عددی را انتخاب شود به شرط آنکه کمتر از طول مجموعه داده باشد.

2. مجموعه داده را به k قسمت مساوی (در صورت امکان) تقسیم می­شود که به آنها folds گفته می شود.

3. k – 1 بسته مجموعه آموزشی خواهد بود. باقیمانده مجموعه تست خواهد بود.

4. مدل بر روی مجموعه آموزشی آموزش داده می­شود. در هر تکرار اعتبار سنجی متقابل، باید یک مدل جدید مستقل از مدل آموزش داده شده در تکرار قبلی آموزش داده شود.

5. در مجموعه تست ارزیابی شود.

6. نتیجه اعتبارسنجی را ذخیره شود.

7. مراحل 3 تا 6 kبار تکرار شود. هر بار از مجموعه باقی مانده را به عنوان مجموعه تست استفاده شود. در پایان، مدل بایستی بر روی هر مجموعه که موجود است اعتبارسنجی شده باشد.

8. برای به دست آوردن امتیاز نهایی، میانگین نتایجی در مرحله 6 مدنظر گرفته شود.

k-Fold cross validation

اعتبار سنجی متقابل k-fold

To perform k-Fold cross-validation you can use sklearn.model_selection.KFold.

برای انجام اعتبارسنجی متقاطع k Fold می توانید ازsklearn.model_selection.KFold استفاده کنید.

import numpy as np
from sklearn.model_selection import KFold
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([1, 2, 3, 4])
kf = KFold(n_splits=2)
for train_index, test_index in kf.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

In general, it is always better to use k-Fold technique instead of hold-out. In a head to head, comparison k-Fold gives a more stable and trustworthy result since training and testing is performed on several different parts of the dataset. We can make the overall score even more robust if we increase the number of folds to test the model on many different sub-datasets.

به طور کلی همیشه بهتر است از تکنیک k-Fold به جای روش برگزاری استفاده شود. از آنجایی که آموزش و تست بر روی تمامی بخش­های مختلف مجموعه داده انجام می شود الگوریتم k-Fold نتیجه پایدارتر و قابل اعتمادتری به دست می­دهد. افزایش تعداد foldها برای آزمایش مدل در مجموعه‌های مختلف‌ می­توان میزان امتیاز کلی را بهبود بخشید.

Still, k-Fold method has a disadvantage. Increasing k results in training more models and the training process might be really expensive and time-consuming.

با این حال، روش K-Fold یک نقطه ضعف دارد. افزایش k منجر به آموزش مدل­های بیشتر می شود و فرآیند آموزش ممکن است واقعاً هزینه­بر و زمانبر باشد.

Leave-one-out

اعتبارسنجی یکطرفه

Leave-one-out cross-validation (LOOCV) is an extreme case of k-Fold CV. Imagine if k is equal to n where n is the number of samples in the dataset. Such k-Fold case is equivalent to Leave-one-out technique.

اعتبارسنجی متقابل یکطرفه[11] (LOOCV) یک مورد دقیق­تر از روش اعتبارسنجیK-Fold است، بصورتی که k برابر با n یعنی تعداد­نمونه های مجموعه داده است. در چنین حالتی k-Fold معادل تکنیک Leave one out است.

The algorithm of LOOCV technique:

Choose one sample from the dataset which will be the test set

The remaining n – 1 samples will be the training set

Train the model on the training set. On each iteration, a new model must be trained

Validate on the test set

Save the result of the validation

Repeat steps 1 – 5 n times as for n samples we have n different training and test sets

To get the final score average the results that you got on step 5.

الگوریتم تکنیک LOOCV:

1. یک نمونه از مجموعه داده را انتخاب شود که مجموعه تست خواهد بود

2. n – 1 نمونه باقیمانده مجموعه آموزشی خواهد بود

3. مدل بر روی مجموعه آموزشی، آموزش داده می­شود. در هر تکرار، یک مدل جدید باید آموزش داده شود

4. در مجموعه تست ارزیابی شود.

5. نتیجه ارزیابی ذخیره شود

6. مراحل 1 تا 5 n بار تکرار شود، همانطور که برای n نمونه، n مجموعه آموزشی و تست متفاوت داریم.

7. برای به دست آوردن امتیاز نهایی، میانگین نتایج در مرحله 5 به دست آورده شود.

Leave-one-out сross-validation

ارزیابی اعتبارسنجی یکطرفه

For LOOCV sklearn also has a built-in method. It can be found in the model_selection library – sklearn.model_selection.LeaveOneOut.

برای LOOCV همچنین دارای یک روش داخلی است. می توان آن را در کتابخانهmodel_selection - sklearn.model_selection.LeaveOneOut پیدا کرد.

import numpy as np
from sklearn.model_selection import LeaveOneOut
X = np.array([[1, 2], [3, 4]])
y = np.array([1, 2])
loo = LeaveOneOut()
for train_index, test_index in loo.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

The greatest advantage of Leave-one-out cross-validation is that it doesn’t waste much data. We use only one sample from the whole dataset as a test set, whereas the rest is the training set. But when compared with k-Fold CV, LOOCV requires building n models instead of k models, when we know that n which stands for the number of samples in the dataset is much higher than k. It means LOOCV is more computationally expensive than k-Fold, it may take plenty of time to cross-validate the model using LOOCV.

بزرگترین مزیت اعتبارسنجی متقابل یکطرفه این است که داده های زیادی هدر نمی­رود. فقط از یک نمونه از کل مجموعه داده به عنوان یک مجموعه تست استفاده می­شود، در حالی که بقیه مجموعه آموزشی است. اما در مقایسه با k-Fold ، LOOCV نیاز به ساخت n مدل به جای k مدل دارد که تعداد نمونه در مجموعه داده بوده و بسیار بیشتر از k است. این بدان معناست که LOOCV از نظر محاسباتی هزینه بر تر از از k-Fold است و ممکن است زمان زیادی طول بکشد تا اعتبارسنجی متقابل مدل با استفاده از LOOCVانجام شود.

Thus, the Data Science community has a general rule based on empirical evidence and different researches, which suggests that 5- or 10-fold cross-validation should be preferred over LOOCV.

بنابراین، جامعه علوم داده یک قاعده کلی مبتنی بر شواهد تجربی و تحقیقات مختلف دارد که نشان می‌دهد اعتبار سنجی متقاطع 5 یا 10 برابری باید بر LOOCV ترجیح داده شود.

Leave-p-out

اعتبارسنجی خارج از صفحه

Leave-p-out cross-validation (LpOC) is similar to Leave-one-out CV as it creates all the possible training and test sets by using p samples as the test set. All entioned about LOOCV is true and for LpOC.

اعتبارسنجی متقابل خارج از صفحه(LpOC) مشابه روش اعتبارسنجی یکطرفه است زیرا تمام مجموعه‌های آموزشی و تست ممکن را با استفاده از pنمونه‌ به عنوان مجموعه آزمایشی ایجاد می‌کند. تمام موارد ذکر شده در مورد LOOCV و برای LpOC درست است.

Still, it is worth mentioning that unlike LOOCV and k-Fold test sets will overlap for LpOC if p is higher than 1.

با این وجود، شایان ذکر است که بر خلافLOOCV و k-Fold مجموعه‌های تست برای LpOC اگر p بالاتر از 1 باشد، همپوشانی دارند.

The algorithm of LpOC technique:

Choose p samples from the dataset which will be the test set The remaining n – p samples will be the training set Train the model on the training set. On each iteration, a new model must be trained Validate on the test set Save the result of the validationRepeat steps 2 – 5 ? times To get the final score average the results that you got on step 5

الگوریتم تکنیک LpOC:

نمونه های p را از مجموعه داده انتخاب کنید که مجموعه آزمایشی خواهد بود.

n - p نمونه باقیمانده مجموعه آموزشی خواهد بود.

مدل را روی مجموعه آموزشی آموزش دهید. در هر تکرار، یک مدل جدید باید آموزش داده شود

در مجموعه تست ارزیابی شود.

نتیجه ارزیابی ذخیره شود

مراحل 2 تا 5 ? بار را تکرار شود

برای به دست آوردن امتیاز نهایی، میانگین نتایج در مرحله 5 به دست آورده شود.

You can perform Leave-p-out CV using sklearn –sklearn.model_selection.LeavePOut.

می توانید Leave p out CV را با استفاده از sklearn – sklearn.model_selection.LeavePOut انجام دهید.

import numpy as np
from sklearn.model_selection import LeavePOut
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([1, 2, 3, 4])
lpo = LeavePOut(2)
for train_index, test_index in lpo.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

LpOC has all the disadvantages of the LOOCV, but, nevertheless, it’s as robust as LOOCV.

LpOC تمام معایب LOOCV را دارد، اما، با این وجود، به اندازه LOOCV قدرتمند است.

Stratified k-Fold

k-Fold دسته­ای

Sometimes we may face a large imbalance of the target value in the dataset. For example, in a dataset concerning wristwatch prices, there might be a larger number of wristwatches having a high price. In the case of classification, in cats and dog’s dataset there might be a large shift towards the dog class.

گاهی اوقات ممکن است با عدم تعادل زیادی در تابع هدف[12]در مجموعه داده مواجه شویم. به عنوان مثال، در مجموعه داده‌های مربوط به قیمت ساعت‌های مچی، ممکن است تعداد بیشتری از ساعت‌های مچی قیمت بالایی داشته باشند. در مورد دسته­بندی، در مجموعه داده‌های گربه‌ها و سگ‌ها ممکن است تغییر زیادی به سمت طبقه سگ وجود داشته باشد.

Stratified k-Fold is a variation of the standard k-Fold CV technique which is designed to be effective in such cases of target imbalance.

k-Fold دسته­ای گونه ای از روش استاندارد k-Fold است منتهی به گونه ای طراحی شده است که در چنین مواردی که تابع هدف تعادل ندارد موثر باشد.

It works as follows. Stratified k-Fold splits the dataset on k folds such that each fold contains approximately the same percentage of samples of each target class as the complete set. In the case of regression, Stratified k-Fold makes sure that the mean target value is approximately equal in all the folds.

این روش به صورت زیر عمل می کند. K-Fold دسته­ای مجموعه داده را بر روی k دسته تقسیم می کند به طوری که هر foldتقریباً دارای درصد مشابهی از نمونه­های هر کلاس هدف به عنوان مجموعه کامل است. در مورد رگرسیون، k-Fold لایه­ای اطمینان حاصل می کند که میانگین تابع هدف تقریباً در همه دسته­ها برابر است.

The algorithm of Stratified k-Fold technique:

Pick a number of folds – k

Split the dataset into k folds. Each fold must contain approximately the same percentage of samples of each target class as the complete set

Choose k – 1 folds which will be the training set. The remaining fold will be the test set

Train the model on the training set. On each iteration a new model must be trained

Validate on the test set

Save the result of the validation

Repeat steps 3 – 6 k times. Each time use the remaining fold as the test set. In the end, you should have validated the model on every fold that you have.

To get the final score average the results that you got on step 6.

الگوریتم تکنیک k-Fold دسته­ای:

1. تعدادی k دسته را انتخاب کنید

2. مجموعه داده را به k برابر تقسیم کنید. هر فولد باید تقریباً دارای درصد مشابهی از نمونه‌های هر کلاس تابع هدف در مجموعه کامل باشد.

3. k – 1 باقی­مانده مجموعه تست خواهد بود.

4. مدل را روی مجموعه آموزشی آموزش دهید. در هر تکرار یک مدل جدید باید آموزش داده شود

5. در مجموعه تست ارزیابی شود.

6. نتیجه ارزیابی ذخیره شود

7. مراحل را 3 تا 6 هزار بار تکرار کنید. هر بار از دسته باقی مانده به عنوان مجموعه تست استفاده کنید. در پایان، شما باید مدل را روی هر دسته که دارید اعتبارسنجی کرده باشید.

8. برای به دست آوردن امتیاز نهایی، میانگین نتایج در مرحله 6 به دست آورده شود.

As you may have noticed, the algorithm for Stratified k-Fold technique is similar to the standard k-Folds. You don’t need to code something additionally as the method will do everything necessary for you.

همانطور که ممکن است متوجه شده باشید، الگوریتم تکنیک k Foldدسته­ای مشابه K-Folds استاندارد است. نیازی به کدنویسی اضافی نیست زیرا این روش همه کارهای لازم را برای شما انجام می دهد.

Stratified k-Fold also has a built-in method in sklearn – sklearn.model_selection.StratifiedKFold.

k-Fold دسته­ای همچنین یک متد داخلی در sklearn دارد یعنی:sklearn.model_selection.StratifiedKFold.

import numpy as np
from sklearn.model_selection import StratifiedKFold
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 1, 1])
skf = StratifiedKFold(n_splits=2)
for train_index, test_index in skf.split(X, y):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

All mentioned above about k-Fold CV is true for Stratified k-Fold technique. When choosing between different CV methods, make sure you are using the proper one. For example, you might think that your model performs badly simply because you are using k-Fold CV to validate the model which was trained on the dataset with a class imbalance. To avoid that you should always do a proper exploratory data analysis on your data.

تمام ویژگی­های ذکرشده روش­های Fold برای تکنیک k-Fold دسته­ای صادق نیز است. هنگام انتخاب بین روش های مختلف اعتبارسنجی، اطمینان حاصل شود که از روش مناسب استفاده می­شود. به عنوان مثال، در زمانی که مدل شما دچار مشکل تعادل در آموزش داده شده است، دلیل آن این است که از روشk-Fold برای اعتبارسنجی مدلی که بر روی مجموعه داده استفاده شده است. برای جلوگیری از چنین مواردی همیشه باید یک تجزیه و تحلیل داده های اکتشافی مناسب روی داده ها انجام شود.

Repeated k-Fold

k-Fold مکرر

Repeated k-Fold cross-validation or Repeated random sub-samplings CV is probably the most robust of all CV techniques in this paper. It is a variation of k-Fold but in the case of Repeated k-Folds k is not the number of folds. It is the number of times we will train the model.

اعتبارسنجی متقابل k-Fold مکرر یا اعتبار سنجی به روش زیرنمونه‌برداری تصادفی احتمالاً قوی‌ترین تکنیک اعتبارسنجی در این مقاله است که نوعی از k-Fold بوده اما در k-Folds مکرر، k بیانگر تعداد دسته­ها نیست، بلکه تعداد دفعاتی است که ما مدل را آموزش خواهیم داد.

The general idea is that on every iteration we will randomly select samples all over the dataset as our test set. For example, if we decide that 20% of the dataset will be our test set, 20% samples will be randomly selected and the rest 80% will become the training set.

ایده کلی این است که در هر تکرار، نمونه‌هایی را به‌طور تصادفی از سرتاسر مجموعه داده به عنوان مجموعه تست انتخاب می‌کنیم. به عنوان مثال، اگر تصمیم بگیریم که 20درصد از مجموعه داده ها مجموعه تست باشند، 20 درصد نمونه به طور تصادفی انتخاب می شوند و 80 درصد بقیه به مجموعه تست تبدیل می شوند.

The algorithm of Repeated k-Fold technique:

Pick k – a number of times the model will be trained

Pick a number of samples which will be the test set

Split the dataset

Train on the training set. On each iteration of cross-validation, a new model must be trained

Validate on the test set

Save the result of the validation

Repeat steps 3-6 k times

To get the final score average the results that you got on step 6.

الگوریتم تکنیک k-Foldمکرر

1. عدد k را انتخاب کنید برای اینکه مشخص شود چند بار مدل آموزش داده خواهد شد

2. تعدادی نمونه را انتخاب کنید که مجموعه تست خواهد بود

3. مجموعه داده را تقسیم کنید

4. روی مجموعه آموزشی عمل یادگیری را انجام دهید. در هر تکرار اعتبارسنجی ، یک مدل جدید باید آموزش داده شود.

5. در مجموعه تست ارزیابی کنید

6. نتیجه اعتبارسنجی را ذخیره کنید

7. مراحل 3 را 6 k بار تکرار کنید

8. برای به دست آوردن امتیاز نهایی، میانگین نتایج در مرحله 6 را به دست آوردید.

Repeated k-Fold

K-Fold مکرر

Repeated k-Fold has clear advantages over standard k-Fold CV. Firstly, the proportion of train/test split is not dependent on the number of iterations. Secondly, we can even set unique proportions for every iteration. Thirdly, random selection of samples from the dataset makes Repeated k-Fold even more robust to selection bias.

تکرار k-Fold مزایای واضحی نسبت به روش استاندارد K-Fold دارد. اولا، نسبت تقسیم آموزش/تست به تعداد تکرارها بستگی ندارد. دوم می توان نسبت های منحصر به فردی را برای هر تکرار تنظیم کرد. سوم، انتخاب تصادفی نمونه‌ها از مجموعه داده، k-Fold مکرر را برای انتخاب قاطع تر سوق می­دهد.

Still, there are some disadvantages. k-Fold CV guarantees that the model will be tested on all samples, whereas Repeated k-Fold is based on randomization which means that some samples may never be selected to be in the test set at all. At the same time, some samples might be selected multiple times.

با این حال، برخی از معایب وجود دارد. روش استاندارد k Fold تضمین می‌کند که مدل بر روی همه نمونه‌ها آزمایش می‌شود، در حالی که k-Fold مکرر بر اساس تصادفی‌سازی است که به این معنی است که برخی از نمونه‌ها ممکن است هرگز برای قرار گرفتن در مجموعه آزمایشی انتخاب نشوند. در همین حال برخی از نمونه ها ممکن است چندین بار انتخاب شوند.

Sklearn will help you to implement Repeated k-Fold CV. Just use sklearn.model_selection.RepeatedKFold. In sklearn implementation of this technique you must set the number of folds that you want to have (n_splits) and the number of times the split will be performed (n_repeats). It guarantees that you will have different folds on each iteration.

Sklearn به شما در پیاده سازی اعتبارسنجی kFold مکررکمک میکند. فقط ازsklearn.model_selection.RepeatedKFold استفاده کنید. در اجرای sklearn این تکنیک باید تعداد بسته­هایی که می خواهید داشته باشید (n_splits) و تعداد دفعاتی که تقسیم انجام می شود (n_repeats) را تنظیم کنید. این تضمین می کند که در هر تکرار بسته­های مختلفی خواهید داشت.

import numpy as np
from sklearn.model_selection import RepeatedKFold
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 1, 1])
rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=42)
for train_index, test_index in rkf.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

Nested k-Fold

تو در تو K Fold

Unlike the other CV techniques, which are designed to evaluate the quality of an algorithm, Nested k-Fold CV is the most popular way to tune the parameters of an algorithm.

برخلاف سایر تکنیک‌های اعتبارسنجی که برای ارزیابی کیفیت یک الگوریتم طراحی شده‌اند، k-Foldتودرتو محبوب‌ترین راه برای تنظیم پارامترهای یک الگوریتم است.

Imagine that we have a parameter p which usually depends on the base algorithm that we are cross-validating. For example, for Logistic Regression it might be the penalty parameter which is used to specify the norm used in the penalization.

تصور کنید که ما یک پارامتر p داریم که معمولاً به الگوریتم پایه ای که ما در حال اعتبارسنجی آن هستیم بستگی دارد. به عنوان مثال، برای رگرسیون لجستیک، ممکن است این پارامتر جریمه باشد که برای تعیین نرم مورد استفاده در جریمه استفاده می شود.

The algorithm of Nested k-Fold technique:

Pick k – a number of folds, for example, 10 – let’s assume that we’ve picked this number

Pick a parameter p. Let’s assume that our algorithm is Logistic Regression and p is the penalty parameter p = {‘l1’, ‘l2’, ‘elasticnet’, ‘none’}

Divide the dataset into 10 folds and reserve one of them for test

Reserve one of the training folds for validation

For each value of p train on the 8 remaining training folds and evaluate on the validation fold. You now have 4 measurements

Repeat steps 4-5 9 times. Rotate which training fold is the validation fold. You now have 9 * 4 measurements

Choose p that minimizes the average training error over 9 folds. Use that p to evaluate on the test set

Repeat 10 times from step 2, using each fold in turn as the test fold

Save the mean and standard deviation of the evaluation measure over the 10 test folds

The algorithm that performed the best was the one with the best average out-of-sample performance across the 10 test folds

الگوریتم تکنیک k-Fold تودرتو:

1. k را انتخاب کنید - تعداد بسته­ها، به عنوان مثال 10 - فرض کنیم این عدد را انتخاب کرده ایم

2. یک پارامتر p را انتخاب کنید. فرض کنید الگوریتم ما رگرسیون لجستیک و p پارامتر جریمه باشد

3. p = {'l1', 'l2', 'elasticnet', 'none'}

4. مجموعه داده را به 10 بسته تقسیم کنید و یکی از آنها را برای تست کنار بگذارید

5. یکی از بسته­های آموزشی را برای ارزیابی کنار بگذارید

6. برای هر مقدار p روی 8 بسته آموزشی باقیمانده آموزش دهید و روی بسته ارزیابی را مورد ارزیابی قرار دهید. اکنون 4 اندازه گیری دارید.

7. مراحل 4 و 5 را 9 بار تکرار کنید. بسته آموزشی را عوض کنید به گونه­ای که بسته ازیابی تغییرکنداست. اکنون اندازه گیری 9 * 4 دارید

8. از مرحله 2 این کار ار 10 بار تکرار کنید و از هر بسته به نوبت به عنوان بسته تست استفاده کنید.

9. میانگین و انحراف معیار اندازه گیری ارزیابی را در 10 بسته تست ذخیره کنید.

10. الگوریتمی بهترین عملکرد را دارد که بهترین میانگین را در بین عملکرد نمونه خارج شده در 10 بسته تست داشته باشد.

This technique is computationally expensive because throughout steps 1 – 10 plenty of models should be trained and evaluated. Still, Nested k-Fold CV is commonly used and might be really effective across multiple ML tasks.

این تکنیک از نظر محاسباتی گران است زیرا در طول مراحل 1 تا 10 تعداد زیادی مدل باید آموزش و ارزیابی شوند. با این حال، اعتبارسنجی k Foldتودرتو معمولا مورد استفاده قرار می­گیرد و ممکن است در چندین کابرد یادگیری ماشین واقعاً مؤثر باشد.

Unfortunately, there is no built-in method in sklearn that would perform Nested k-Fold CV for you. This’s the moment when you should either Google and find someone’s implementation or code it yourself.

متأسفانه، هیچ روش داخلی درsklearn وجود ندارد که بتواند k-Fold تودرتو را برای شما انجام دهد. این لحظه ای است که شما باید یا گوگل کنید و پیاده سازی شخصی را پیدا کنید یا خودتان آن را کدنویسی کنید.

Complete Cross-Validation

اعتبارسنجی متقابل کامل

Complete CV is the least used CV technique. The general idea is that we choose a number k – the length of the training set and validate on every possible split containing k samples in the training set.

اعتبارسنجی متقابل کامل کم استفاده ترین تکنیک اعتبارسنجی است. ایده کلی این است که ما یک عدد k را که طول مجموعه آموزشی است را انتخاب می­کنیم و روی هر تقسیم ممکن که شامل k نمونه در مجموعه آموزشی است اعتبار سنجی می کنیم.

The amount of those splits can be calculated as Сnk where n is the length of the dataset. If k is higher than 2, we will have to train our model plenty of times which as we have already figured out is an expensive procedure time and computation-wise.

مقدار آن تقسیم‌ها را می‌توان به صورت ?محاسبه کرد که n طول مجموعه داده است. اگر k بیش از 2 باشد، باید مدل خود را بارها آموزش دهیم که همانطور که قبلاً متوجه شدیم از نظر زمان و محاسبات گران قیمت است.

This is why Complete CV is used either in theoretical researches or if there is an effective formula that will help to minimize the calculations.

به همین دلیل است که از اعتبارسنجی کامل یا در تحقیقات نظری استفاده می شود و یا مورد استفاده قرار می­گیرد که فرمول مؤثری که به حداقل رساندن محاسبات وجود داشته باشد.

The algorithm of Complete cross-validation:

Pick a number k – length of the training set

Split the dataset

Train on the training set

Validate on the test set

Save the result of the validation

Repeat steps 2 – 5 Сnk times

To get the final score average the results that you got on step 5

الگوریتم اعتبار سنجی متقابل کامل:

1. یک عدد k را انتخاب کنید - طول مجموعه آموزشی

2. مجموعه داده را تقسیم کنید

3. روی مجموعه آموزشی عمل یادگیری را انجام دهید کنید

4. در مجموعه تسس ارزیابی کنید

5. نتیجه اعتبارسنجی را ذخیره کنید

6. مراحل 2 تا 5 ?را تکرار کنید

7. برای به دست آوردن امتیاز نهایی، میانگین نتایج در مرحله 5 را به دست آوردید

Cross-Validation in Machine Learning

اعتبارسنجی متقابل در یادگیری ماشینی

Most of the cross-validation techniques mentioned above are widely used in ML. It’s important to remember that using the proper CV technique may save you a lot of time and help to select the best model for the task.

بیشتر تکنیک های اعتبارسنجی متقابل ذکر شده در بالا به طور گسترده در یادگیری ماشین استفاده می شود. مهم است که به خاطر داشته باشید که استفاده از تکنیک اعتبارسنجی مناسب ممکن است باعث صرفه جویی شما در زمان شود و حتی به انتخاب بهترین مدل برای کار کمک کند.

It means that, firstly, it’s better to always cross-validate the model and, secondly, you should choose a relevant CV method. Thus, knowing the benefits and disadvantages of cross-validation techniques is vital.

این بدان معناست که اولاً بهتر است همیشه مدل را اعتبارسنجی کنید و ثانیاً باید یک روش اعتبار سنجی مرتبط را انتخاب کنید. بنابراین، دانستن مزایا و معایب تکنیک‌های اعتبارسنجی متقابل حیاتی است.

It’s worth mentioning that if you want to cross-validate the model you should always check the model’s manual because some ML algorithms, for example, CatBoost have their own built-in CV methods. You may find them relevant for your ML task and use them instead of sklearn built-in methods.

شایان ذکر است که اگر مدل را اعتبار سنجی کنید، همیشه باید راهنمای مدل را بررسی کنید زیرا برخی از الگوریتم‌های یادگیری ماشین به عنوان مثال، CatBoost روش‌های اعتبارسنجی خود را دارند. شما ممکن است آنها را مرتبط به وظیفه برنامه یادگیری ماشین خود بیابید و از آنها به جای متدهایsklearn استفاده کنید.

In general, as you may have noticed many CV techniques have sklearn built-in methods. I strongly recommend using them as these methods will save you plenty of time for more complicated tasks.

به طور کلی، همانطور که ممکن است متوجه شده باشید، بسیاری از تکنیک‌های اعتبارسنجی دارای روش‌های sklearn هستند. به شدت توصیه می­شود که از آنها استفاده کنید زیرا این روش ها در زمان زیادی برای کارهای پیچیده­تر صرفه جویی می­کنند.

Cross-Validation in Deep Learning

اعتبارسنجی متقابل در یادگیری عمیق[13]

Cross-validation in Deep Learning (DL) might be a little tricky because most of the CV techniques require training the model at least a couple of times.

اعتبار سنجی متقاطع در یادگیری عمیق(DL) ممکن است کمی مشکل باشد زیرا اکثر تکنیک های اعتبارسنجی نیاز به آموزش مدل حداقل چند بار دارند.

In deep learning, you would normally tempt to avoid CV because of the cost associated with training k different models. Instead of doing k-Fold or other CV technique, you might use a random subset of your training data as a hold-out for validation purposes.

در یادگیری عمیق، معمولاً به دلیل هزینه‌های مرتبط با آموزش مدل‌های مختلف، از اعتبارسنجی اجتناب می‌شود. به جای انجام k-Fold یا سایر تکنیک‌های اعتبارسنجی، ممکن است از یک زیرمجموعه تصادفی از داده‌های آموزشی خود به عنوان روش برگزاری برای اهداف اعتبارسنجی استفاده شود.

For example, Keras deep learning library allows you to pass one of two parameters for the fit function that performs training.

به عنوان مثال، کتابخانه یادگیری عمیقKeras به شما امکان می دهد یکی از دو پارامتر را برای تابع fit که آموزش را انجام می دهد، ارسال کنید.

validation_split: percentage of the data that should be held out for validation

validation_data: a tuple of (X, y) which should be used for validation. This parameter overrides the validation_split parameter which means you can use only one of these parameters at once.

The same approach is used in official tutorials of other DL frameworks such as PyTorch and MxNet. They also suggest splitting the dataset into three parts: training, validation, and testing.

validation_split درصدی از داده هایی که باید برای اعتبار سنجی نگهداری شوند

validation_data چند عدد از (X, y) که باید برای اعتبارسنجی استفاده شود. این پارامتر پارامتر validation_split را نادیده می گیرد، به این معنی که شما می توانید تنها یکی از این پارامترها را در یک زمان استفاده کنید.

همین رویکرد در آموزش های رسمی سایر فریمورک های DL مانند PyTorch و MxNet استفاده می شود. آنها همچنین پیشنهاد می کنند مجموعه داده را به سه بخش تقسیم کنید: آموزش، اعتبار سنجی و تست.

Training – a part of the dataset to train on

Validation – a part of the dataset to validate on while training

Testing – a part of the dataset for final validation of the model

آموزش – بخشی از مجموعه داده برای آموزش

اعتبار سنجی - بخشی از مجموعه داده برای اعتبارسنجی در حین آموزش

تست - بخشی از مجموعه داده برای اعتبار سنجی نهایی مدل

Still, you can use cross-validation in DL tasks if the dataset is tiny (contains hundreds of samples). In this case, learning a complex model might be an irrelevant task so make sure that you don’t complicate the task further.

با این حال، اگر مجموعه داده کوچک است (شامل صدها نمونه) می توانید از اعتبارسنجی متقابل در وظایف یادگیری عمیق استفاده کنید. در این مورد، یادگیری یک مدل پیچیده ممکن است یک کار بی ربط باشد، بنابراین مطمئن شوید که کار را بیشتر پیچیده نکنید.

Best practices and tips

بهترین روش ها و نکات

It’s worth mentioning that sometimes performing cross-validation might be a little tricky.

شایان ذکر است که گاهی اوقات انجام اعتبارسنجی متقابل ممکن است کمی مشکل باشد.

For example, it’s quite easy to make a logical mistake when splitting the dataset which may lead to an untrustworthy CV result.

به عنوان مثال، اشتباه منطقی هنگام تقسیم مجموعه داده به سادگی صورت می­گیرد که ممکن است منجر به یک اعتبارسنجی غیرقابل اعتماد شود.

You may find some tips that you need to keep in mind when cross-validating a model below:

نکاتی را که باید هنگام اعتبارسنجی متقابل یک مدل مد نظر داشته باشید شامل موارد:

Be logical when splitting the data (does the splitting method make sense)

Use the proper CV method (is this method viable for my use-case)

When working with time series don’t validate on the past (see the first tip)

When working with medical or financial data remember to split by person. Avoid having data for one person both in the training and the test set as it may be considered as data leak

When cropping patches from larger images remember to split by the large image Id

هنگام تقسیم داده ها منطقی عمل کنید (آیا روش تقسیم منطقی است)

از روش اعتبارسنجی مناسب استفاده کنید (آیا این روش برای مورد استفاده من قابل اجرا است)

هنگام کار با سری های زمانی، گذشته را ارزیابی نکنید و مد نظر قرار ندهید(به اولین نکته مراجعه کنید)

هنگام کار با داده های پزشکی یا مالی، به یاد داشته باشید که شخصا تقسیم­بندی کنید. از قرار دادن داده یک نفر هم در آموزش و هم در مجموعه تست خودداری کنید زیرا ممکن است به عنوان داده لو رفته در نظر گرفته شود

هنگام برش تکه‌ها از تصاویر بزرگ‌تر، به یاد داشته باشید که شناسه تصویر بزرگ را نیز تقسیم کنید.

Of course, tips differ from task to task and it’s almost impossible to cover all of them. That’s why performing a solid exploratory data analysis before starting to cross-validate a model is always the best practice.

البته، نکات از کاری به کار دیگر متفاوت است و پوشش همه آنها تقریبا غیرممکن است. به همین دلیل است که انجام یک تجزیه و تحلیل داده های اکتشافی جامد قبل از شروع اعتبارسنجی متقابل یک مدل همیشه بهترین روش و کار است.

Final thoughts

سخن آخر

Cross-validation is a powerful tool. Every Data Scientist should be familiar with it. In real life, you can’t finish the project without cross-validating a model.

اعتبار سنجی متقابل ابزار قدرتمندی است. هر کارشناس داده باید با آن آشنا باشد. در واقعیت، شما نمی توانید پروژه را بدون اعتبارسنجی متقابل یک مدل به پایان برسانید.

In my opinion, the best CV techniques are Nested k-Fold and standard k-Fold. Personally, I used them in the task of Fraud Detection. Nested k-Fold as well as GridSeachCV helped me to tune the parameters of my model. k-Fold on the other hand was used to evaluate my model’s performance.

به نظر من بهترین تکنیک های اعتبارسنجیk-Fold تودرتو و k-Foldاستاندارد هستند. شخصاً از آنها در وظیفه تشخیص تقلب استفاده کردم. K- Fold تو در تو و همچنین GridSeachCV به من کمک کردند تا پارامترهای مدل خود را تنظیم کنم. از طرف دیگر، k-Fold برای ارزیابی عملکرد مدل من استفاده شد.

In this article, we have figured out what cross-validation is, what CV techniques are there in the wild, and how to implement them. In the future ML algorithms will definitely perform even better than today. Still, cross- validation will always be needed to back your results up.

در این مقاله، ما متوجه شدیم که اعتبار سنجی متقابل چیست، چه تکنیک های اعتبارسنجی وجود دارد، و چگونه آنها را پیاده سازی کنیم. در آینده الگوریتم های یادگیری ماشین قطعاً حتی بهتر از امروز عمل خواهند کرد. با این حال، اعتبار سنجی متقابل همیشه برای پشتیبان­گیری از نتایج مورد نیاز است.

Hopefully, with this information, you will have no problems setting up the CV for your next machine learning project!

امیدواریم با این اطلاعات، مشکلی در تنظیم CV برای پروژه بعدی یادگیری ماشین خود نداشته باشید!

منابع

https://www.geeksforgeeks.org/cross-validation-machine-learning/

https://machinelearningmastery.com/k-fold-cross-validation/

https://towardsdatascience.com/cross-validation-in-machine-learning-72924a69872f

https://towardsdatascience.com/why-and-how-to-do-cross-validation-for-machine-learning-d5bd7e60c189

https://scikit-learn.org/stable/modules/cross_validation.html

[1] Machine Learning

[2] Generalization

[3] Cross-Validation

[4] Hold-out Method

[5] Leave-one-out

[6] Leave-p-out

[7] Stratified k-folds

[8] Repeated k-folds

[9] Nested k-folds

[10] Complete CV

[11] Leave One Out Cross Validation

[12] Target Value

[13] Deep Learning

۲
۰
محمدحسین ف
محمدحسین ف
شاید از این پست‌ها خوشتان بیاید