Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

KFold Cross-validation Random Forest Binary Classification

Mon Oct 28, 2019 5:41 am

This is a Supervised Learning using the random forest. The distinctive part of this example in contrast to the previous one (Random Forest Example) is the split of data. In this example, we apply more extensive validation of the model using the KFold Cross-validation. In this validation approach, the model is trained and tested K-times with different training and testing data for each time. In the end, we will have 5 results for 5 models. To report the results, the average or the median of performance measures is usually is selected to represent the outcome of this experiment. The main benefit of KFold Cross-validation is to reduce the chances of overfitting. Generally, the model results from the KFold validation is trained on different combinations of the data. Hence, it has lower chances to be overfitted to a particular training set.


python code
#Demo4
#M. S. Rakha, Ph.D.
# Post-Doctoral - Queen's University
# Supervised Learning - RandomForest Classification
# RandomForest Classification_Kfold
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn.preprocessing import scale
import sklearn.metrics as sm
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

np.random.seed(5)
breastCancer = datasets.load_breast_cancer()

list(breastCancer.target_names)

#Only two features
X = breastCancer.data[:, 0:2]
y = breastCancer.target


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.50, random_state=42)

X_train[:,0].size
X_train[:,0].size

varriableNames= breastCancer.feature_names


from sklearn.model_selection import KFold
from sklearn.model_selection import RepeatedKFold

#Kfold of 5
#No repeations (only once)
kf = RepeatedKFold(n_splits=5, n_repeats=1, random_state=None)
randomForestModel = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)

#Applying the training and testing of the KFold
for train_index, test_index in kf.split(X):
print("Train:", train_index, "Validation:",test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
randomForestModel.fit(X_train, y_train)
y_pred = randomForestModel.predict(X_test)
print(classification_report(y_test, y_pred))



This script is using several machine learning libraries, such as numpy, matplotlib, pandas, and sklearn, to classify breast cancer data using Random Forest classifier. The breast cancer data is loaded from the sklearn datasets library, and only two features from the data set are used for the analysis. The script splits the data into training and testing sets using the train_test_split method from sklearn. Then, it uses the RepeatedKFold class from sklearn.model_selection to perform 5-fold cross-validation, repeated once. The RepeatedKFold class generates indices to split the data into training and test sets for each fold. The script uses the RandomForestClassifier method from sklearn.ensemble to create a random forest model with 100 trees, a maximum depth of 2, and a random state of 0. For each fold, it uses the generated indices to split the data into a training set and a test set, fits the random forest model to the training data, predicts the labels for the test data, and prints out a classification report to evaluate the performance of the model on the test data. The classification report includes metrics such as precision, recall, f1-score, and support for each label.


In the script, the KFold class from sklearn.model_selection is used to perform k-fold cross-validation. The script specifies that it wants to use 5-fold cross-validation, which means that the data will be split into 5 equal-sized folds. For each fold, one of the five parts will be used as the test set, while the other four parts will be used as the training set.
The script initializes a KFold object called 'kf', with the following parameters:

    n_splits: 5, which means that the data will be split into 5 folds.
    n_repeats: 1, which means that the k-fold procedure will be repeated once.
    random_state: None, which means that the random number generator will be initialized with the current system time.
The script then uses the split() method of the KFold object to generate indices to split the data into training and test sets. The split() method returns an iterator yielding pairs of indices corresponding to the training and test sets.
For each fold, it uses the generated indices to split the data into a training set and a test set, fits the random forest model to the training data, predicts the labels for the test data, and prints out a classification report to evaluate the performance of the model on the test data.



The main goal of using cross-validation is to evaluate the performance of a machine-learning model on unseen data. By using k-fold cross-validation, the script can use all of the available data for training and testing, which helps reduce the model performance variance. It allows the script to estimate how well the model will perform on unseen data. The script uses 5-fold cross-validation, which is a widely used method. In 5-fold cross-validation, the data is divided into five equal-sized parts or "folds," The model is trained on 4 of the five parts and tested on the remaining part. This process is repeated five times, with each of the five parts used as the test set once. The script uses the classification_report method to evaluate the performance of the model on each fold. The classification report calculates several performance metrics such as precision, recall, f1-score, and support for each label. These metrics provide insight into the model's performance and help the script understand how well the model can predict the class labels.

The out of this code are indexes of the training set, indexes of the testing set (also called validation), and accuracy measurements for each fold of the 5.

Code:
Train: [  0   1   2   4   5   6   8   9  10  11  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  29  30  31  32  33  35  36  37  38  39  41
  43  44  46  47  48  49  54  55  57  58  59  60  61  62  63  64  65  67
  69  70  71  72  73  74  76  77  78  79  80  81  82  83  85  86  87  88
  89  90  91  92  93  94  95  96  97  98 100 101 102 103 104 105 106 108
109 110 112 113 114 115 117 118 119 120 121 122 125 126 127 128 130 131
133 135 136 137 138 139 141 142 143 144 145 146 147 148 150 152 153 154
156 157 158 159 160 161 164 165 166 167 168 169 171 172 173 174 175 176
177 178 179 180 181 182 183 184 185 188 190 191 192 193 194 195 196 197
200 201 202 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
219 220 221 222 224 225 226 227 229 231 232 233 235 237 238 239 240 241
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 259 260
262 263 264 265 266 267 268 270 271 272 273 274 275 276 277 278 279 280
283 284 285 287 288 289 290 291 292 294 295 296 299 300 301 302 303 304
305 306 307 308 309 310 312 314 315 316 317 319 320 321 322 324 325 326
327 328 330 331 332 334 335 336 337 338 340 341 342 343 344 345 347 348
349 350 351 353 356 357 358 360 362 363 364 365 367 370 371 372 373 374
375 376 377 378 380 381 383 384 385 386 387 389 390 391 393 394 395 396
397 398 399 400 402 404 405 406 407 408 409 410 411 412 413 415 416 418
419 420 422 424 425 427 428 429 430 431 433 435 437 438 439 440 442 444
445 446 447 448 449 450 451 454 456 458 459 460 462 463 464 465 466 467
468 469 470 471 472 473 474 475 476 477 478 481 482 483 484 485 486 487
488 489 491 492 494 496 497 498 499 502 503 504 505 506 508 512 513 514
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 532 533 534
535 536 538 539 540 541 542 544 546 547 548 550 551 552 554 556 558 559
560 561 564 565 568] Validation: [  3   7  12  28  34  40  42  45  50  51  52  53  56  66  68  75  84  99
107 111 116 123 124 129 132 134 140 149 151 155 162 163 170 186 187 189
198 199 203 223 228 230 234 236 258 261 269 281 282 286 293 297 298 311
313 318 323 329 333 339 346 352 354 355 359 361 366 368 369 379 382 388
392 401 403 414 417 421 423 426 432 434 436 441 443 452 453 455 457 461
479 480 490 493 495 500 501 507 509 510 511 515 531 537 543 545 549 553
555 557 562 563 566 567]
              precision    recall  f1-score   support

           0       0.97      0.81      0.89        48
           1       0.88      0.98      0.93        66

    accuracy                           0.91       114
   macro avg       0.93      0.90      0.91       114
weighted avg       0.92      0.91      0.91       114

Train: [  0   1   2   3   4   5   6   7   8  10  11  12  13  14  15  16  17  18
  19  20  22  23  24  25  26  27  28  29  30  31  32  34  35  36  37  38
  39  40  41  42  44  45  46  50  51  52  53  54  55  56  57  58  60  61
  63  64  65  66  67  68  69  70  72  73  74  75  77  78  79  80  81  82
  83  84  85  86  87  88  91  92  93  94  95  96  97  99 100 102 103 104
105 106 107 108 110 111 112 113 114 116 118 119 120 121 123 124 126 128
129 130 132 133 134 135 136 137 138 140 142 143 144 146 147 148 149 151
152 154 155 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
172 173 174 175 177 178 180 181 182 183 184 185 186 187 188 189 190 191
192 193 194 196 198 199 200 202 203 204 205 206 207 209 210 211 213 214
215 216 217 220 221 222 223 225 226 227 228 229 230 231 233 234 235 236
237 238 239 240 241 243 245 246 249 250 251 252 253 254 255 256 257 258
259 260 261 262 263 264 265 266 267 268 269 270 271 272 274 275 276 277
278 281 282 283 284 286 287 290 291 293 294 296 297 298 300 307 308 309
310 311 313 314 315 318 319 320 322 323 324 325 326 329 330 332 333 334
335 336 337 338 339 340 342 343 346 347 348 349 350 351 352 353 354 355
356 359 360 361 362 363 364 365 366 367 368 369 370 371 372 374 375 377
378 379 380 382 384 385 386 387 388 389 391 392 393 394 396 397 398 399
400 401 402 403 404 405 406 407 408 409 411 412 413 414 415 416 417 418
420 421 423 424 426 429 430 431 432 433 434 436 437 438 441 442 443 446
449 450 451 452 453 454 455 456 457 459 461 462 463 466 468 470 471 473
474 475 476 477 478 479 480 482 483 485 486 487 488 489 490 491 492 493
495 496 497 500 501 502 503 505 507 508 509 510 511 512 514 515 516 517
518 519 520 521 522 528 530 531 532 534 535 536 537 538 539 540 541 542
543 544 545 547 548 549 550 551 552 553 555 556 557 558 560 561 562 563
564 565 566 567 568] Validation: [  9  21  33  43  47  48  49  59  62  71  76  89  90  98 101 109 115 117
122 125 127 131 139 141 145 150 153 156 176 179 195 197 201 208 212 218
219 224 232 242 244 247 248 273 279 280 285 288 289 292 295 299 301 302
303 304 305 306 312 316 317 321 327 328 331 341 344 345 357 358 373 376
381 383 390 395 410 419 422 425 427 428 435 439 440 444 445 447 448 458
460 464 465 467 469 472 481 484 494 498 499 504 506 513 523 524 525 526
527 529 533 546 554 559]
              precision    recall  f1-score   support

           0       0.92      0.83      0.87        29
           1       0.94      0.98      0.96        85

    accuracy                           0.94       114
   macro avg       0.93      0.90      0.92       114
weighted avg       0.94      0.94      0.94       114

Train: [  1   2   3   5   7   8   9  12  13  14  16  19  20  21  22  23  27  28
  29  30  31  32  33  34  35  36  37  40  41  42  43  44  45  47  48  49
  50  51  52  53  54  56  57  59  62  63  64  65  66  68  69  70  71  72
  73  74  75  76  77  78  80  82  84  85  86  87  89  90  91  93  94  95
  97  98  99 100 101 103 104 105 107 109 110 111 113 114 115 116 117 118
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 139
140 141 142 143 144 145 146 147 148 149 150 151 153 154 155 156 159 160
162 163 165 166 167 169 170 171 172 173 175 176 177 178 179 180 181 183
186 187 188 189 190 192 193 194 195 196 197 198 199 200 201 202 203 204
205 206 207 208 210 211 212 214 215 216 217 218 219 220 223 224 225 228
229 230 232 233 234 235 236 239 242 243 244 245 246 247 248 249 252 254
255 256 257 258 259 260 261 264 265 266 268 269 270 271 273 274 276 279
280 281 282 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
299 301 302 303 304 305 306 308 311 312 313 314 315 316 317 318 320 321
323 324 325 326 327 328 329 331 332 333 335 337 338 339 341 344 345 346
347 348 350 352 353 354 355 357 358 359 360 361 362 364 366 367 368 369
370 372 373 374 376 377 378 379 380 381 382 383 384 385 386 387 388 389
390 391 392 393 395 396 397 398 399 400 401 403 406 407 408 410 411 412
413 414 416 417 418 419 421 422 423 424 425 426 427 428 430 431 432 433
434 435 436 437 438 439 440 441 443 444 445 446 447 448 449 451 452 453
454 455 456 457 458 459 460 461 462 464 465 466 467 469 470 472 473 474
475 476 479 480 481 482 484 485 487 488 489 490 491 492 493 494 495 498
499 500 501 504 505 506 507 508 509 510 511 512 513 515 516 518 519 520
522 523 524 525 526 527 528 529 530 531 532 533 535 537 539 540 542 543
544 545 546 547 548 549 550 551 552 553 554 555 556 557 559 560 562 563
564 565 566 567 568] Validation: [  0   4   6  10  11  15  17  18  24  25  26  38  39  46  55  58  60  61
  67  79  81  83  88  92  96 102 106 108 112 119 137 138 152 157 158 161
164 168 174 182 184 185 191 209 213 221 222 226 227 231 237 238 240 241
250 251 253 262 263 267 272 275 277 278 283 300 307 309 310 319 322 330
334 336 340 342 343 349 351 356 363 365 371 375 394 402 404 405 409 415
420 429 442 450 463 468 471 477 478 483 486 496 497 502 503 514 517 521
534 536 538 541 558 561]
              precision    recall  f1-score   support

           0       0.88      0.88      0.88        42
           1       0.93      0.93      0.93        72

    accuracy                           0.91       114
   macro avg       0.91      0.91      0.91       114
weighted avg       0.91      0.91      0.91       114

Train: [  0   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  21
  22  24  25  26  27  28  29  31  32  33  34  35  38  39  40  41  42  43
  44  45  46  47  48  49  50  51  52  53  55  56  58  59  60  61  62  64
  65  66  67  68  71  72  73  75  76  78  79  80  81  82  83  84  86  88
  89  90  92  94  96  98  99 101 102 103 105 106 107 108 109 110 111 112
113 115 116 117 118 119 120 122 123 124 125 126 127 129 131 132 134 135
137 138 139 140 141 144 145 146 147 149 150 151 152 153 155 156 157 158
160 161 162 163 164 165 168 170 172 174 175 176 177 179 180 182 183 184
185 186 187 188 189 190 191 195 197 198 199 201 203 204 205 206 207 208
209 210 212 213 214 216 218 219 220 221 222 223 224 225 226 227 228 230
231 232 233 234 235 236 237 238 239 240 241 242 244 245 247 248 250 251
253 254 258 260 261 262 263 264 265 267 269 272 273 274 275 276 277 278
279 280 281 282 283 285 286 288 289 292 293 294 295 297 298 299 300 301
302 303 304 305 306 307 308 309 310 311 312 313 314 316 317 318 319 321
322 323 324 325 326 327 328 329 330 331 332 333 334 336 337 338 339 340
341 342 343 344 345 346 347 348 349 351 352 354 355 356 357 358 359 361
362 363 364 365 366 367 368 369 371 372 373 374 375 376 377 379 380 381
382 383 384 387 388 389 390 391 392 394 395 397 398 400 401 402 403 404
405 406 408 409 410 411 414 415 417 418 419 420 421 422 423 425 426 427
428 429 431 432 433 434 435 436 437 439 440 441 442 443 444 445 446 447
448 449 450 452 453 455 457 458 459 460 461 463 464 465 467 468 469 471
472 474 476 477 478 479 480 481 483 484 485 486 487 490 491 493 494 495
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 513 514
515 517 518 519 521 522 523 524 525 526 527 529 531 532 533 534 536 537
538 539 541 542 543 544 545 546 549 550 552 553 554 555 556 557 558 559
561 562 563 566 567] Validation: [  1   2  19  20  23  30  36  37  54  57  63  69  70  74  77  85  87  91
  93  95  97 100 104 114 121 128 130 133 136 142 143 148 154 159 166 167
169 171 173 178 181 192 193 194 196 200 202 211 215 217 229 243 246 249
252 255 256 257 259 266 268 270 271 284 287 290 291 296 315 320 335 350
353 360 370 378 385 386 393 396 399 407 412 413 416 424 430 438 451 454
456 462 466 470 473 475 482 488 489 492 512 516 520 528 530 535 540 547
548 551 560 564 565 568]
              precision    recall  f1-score   support

           0       0.94      0.74      0.83        43
           1       0.86      0.97      0.91        71

    accuracy                           0.89       114
   macro avg       0.90      0.86      0.87       114
weighted avg       0.89      0.89      0.88       114

Train: [  0   1   2   3   4   6   7   9  10  11  12  15  17  18  19  20  21  23
  24  25  26  28  30  33  34  36  37  38  39  40  42  43  45  46  47  48
  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  66  67  68
  69  70  71  74  75  76  77  79  81  83  84  85  87  88  89  90  91  92
  93  95  96  97  98  99 100 101 102 104 106 107 108 109 111 112 114 115
116 117 119 121 122 123 124 125 127 128 129 130 131 132 133 134 136 137
138 139 140 141 142 143 145 148 149 150 151 152 153 154 155 156 157 158
159 161 162 163 164 166 167 168 169 170 171 173 174 176 178 179 181 182
184 185 186 187 189 191 192 193 194 195 196 197 198 199 200 201 202 203
208 209 211 212 213 215 217 218 219 221 222 223 224 226 227 228 229 230
231 232 234 236 237 238 240 241 242 243 244 246 247 248 249 250 251 252
253 255 256 257 258 259 261 262 263 266 267 268 269 270 271 272 273 275
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 295
296 297 298 299 300 301 302 303 304 305 306 307 309 310 311 312 313 315
316 317 318 319 320 321 322 323 327 328 329 330 331 333 334 335 336 339
340 341 342 343 344 345 346 349 350 351 352 353 354 355 356 357 358 359
360 361 363 365 366 368 369 370 371 373 375 376 378 379 381 382 383 385
386 388 390 392 393 394 395 396 399 401 402 403 404 405 407 409 410 412
413 414 415 416 417 419 420 421 422 423 424 425 426 427 428 429 430 432
434 435 436 438 439 440 441 442 443 444 445 447 448 450 451 452 453 454
455 456 457 458 460 461 462 463 464 465 466 467 468 469 470 471 472 473
475 477 478 479 480 481 482 483 484 486 488 489 490 492 493 494 495 496
497 498 499 500 501 502 503 504 506 507 509 510 511 512 513 514 515 516
517 520 521 523 524 525 526 527 528 529 530 531 533 534 535 536 537 538
540 541 543 545 546 547 548 549 551 553 554 555 557 558 559 560 561 562
563 564 565 566 567 568] Validation: [  5   8  13  14  16  22  27  29  31  32  35  41  44  64  65  72  73  78
  80  82  86  94 103 105 110 113 118 120 126 135 144 146 147 160 165 172
175 177 180 183 188 190 204 205 206 207 210 214 216 220 225 233 235 239
245 254 260 264 265 274 276 294 308 314 324 325 326 332 337 338 347 348
362 364 367 372 374 377 380 384 387 389 391 397 398 400 406 408 411 418
431 433 437 446 449 459 474 476 485 487 491 505 508 518 519 522 532 539
542 544 550 552 556]

              precision    recall  f1-score   support

           0       0.89      0.62      0.73        50
           1       0.76      0.94      0.84        63

    accuracy                           0.80       113
   macro avg       0.82      0.78      0.78       113
weighted avg       0.81      0.80      0.79       113






Post a reply
  Related Posts  to : KFold Cross-validation Random Forest Binary Classification
 Random Forest Classification (Binary )- Supervised Learning     -  
 Weka java code for Random Forest Cross Validation     -  
 Naive Bayes Classification (Binary )- Supervised Learning     -  
 random forest algorithm classifier     -  
 Get the important variables of random forest classifier     -  
 R script for RandomForest with Cross-validation and Sampling     -  
 Cost Sensitive Classifier Random Forest Java in weka     -  
 Cross platform c++ programming     -  
 binary search     -  
 convert to binary number     -  

Topic Tags

Machine Learning, Artificial Intelligence