1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
|
#' @title Performance measures.
#'
#' @description
#' A performance measure is evaluated after a single train/predict step and
#' returns a single number to assess the quality of the prediction (or maybe
#' only the model, think AIC). The measure itself knows whether it wants to be
#' minimized or maximized and for what tasks it is applicable.
#'
#' All supported measures can be found by [listMeasures] or as a table in the
#' tutorial appendix: <https://mlr.mlr-org.com/articles/tutorial/measures.html>.
#'
#' If you want a measure for a misclassification cost matrix, look at
#' [makeCostMeasure]. If you want to implement your own measure, look at
#' [makeMeasure].
#'
#' Most measures can directly be accessed via the function named after the
#' scheme measureX (e.g. measureSSE).
#'
#' For clustering measures, we compact the predicted cluster IDs such that they
#' form a continuous series starting with 1. If this is not the case, some of
#' the measures will generate warnings.
#'
#' Some measure have parameters. Their defaults are set in the constructor
#' [makeMeasure] and can be overwritten using [setMeasurePars].
#'
#' @param truth ([factor])\cr
#' Vector of the true class.
#' @param response ([factor])\cr
#' Vector of the predicted class.
#' @param negative (`character(1)`)\cr
#' The name of the negative class.
#' @param positive (`character(1)`)\cr
#' The name of the positive class.
#' @param probabilities ([numeric] | [matrix])\cr
#' a) For purely binary classification measures: The predicted probabilities for the positive class as a numeric vector.
#' b) For multiclass classification measures: The predicted probabilities for all classes, always as a numeric matrix, where
#' columns are named with class labels.
#' @name measures
#' @family performance
NULL
###############################################################################
### general ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
featperc = makeMeasure(
id = "featperc", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "classif.multi", "multilabel", "regr", "surv", "costsens", "cluster", "req.model", "req.pred"),
name = "Percentage of original features used for model",
note = "Useful for feature selection.",
fun = function(task, model, pred, feats, extra.args) {
length(model$features) / sum(pred$task.desc$n.feat)
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
timetrain = makeMeasure(
id = "timetrain", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "classif.multi", "multilabel", "regr", "surv", "costsens", "cluster", "req.model"),
name = "Time of fitting the model",
fun = function(task, model, pred, feats, extra.args) {
model$time
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
timepredict = makeMeasure(
id = "timepredict", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "classif.multi", "multilabel", "regr", "surv", "costsens", "cluster", "req.pred"),
name = "Time of predicting test set",
fun = function(task, model, pred, feats, extra.args) {
pred$time
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
timeboth = makeMeasure(
id = "timeboth", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "classif.multi", "multilabel", "regr", "surv", "costsens", "cluster", "req.model", "req.pred"),
name = "timetrain + timepredict",
fun = function(task, model, pred, feats, extra.args) {
model$time + pred$time
}
)
###############################################################################
### regression ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
sse = makeMeasure(
id = "sse", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Sum of squared errors",
note = "Defined as: sum((response - truth)^2)",
fun = function(task, model, pred, feats, extra.args) {
measureSSE(pred$data$truth, pred$data$response)
}
)
#' @export measureSSE
#' @rdname measures
measureSSE = function(truth, response) {
sum((response - truth)^2)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mse = makeMeasure(
id = "mse", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Mean of squared errors",
note = "Defined as: mean((response - truth)^2)",
fun = function(task, model, pred, feats, extra.args) {
measureMSE(pred$data$truth, pred$data$response)
}
)
#' @export measureMSE
#' @rdname measures
measureMSE = function(truth, response) {
mean((response - truth)^2)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
rmse = makeMeasure(
id = "rmse", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Root mean squared error",
note = "The RMSE is aggregated as sqrt(mean(rmse.vals.on.test.sets^2)). If you don't want that, you could also use `test.mean`.",
fun = function(task, model, pred, feats, extra.args) {
measureRMSE(pred$data$truth, pred$data$response)
},
aggr = test.rmse
)
#' @export measureRMSE
#' @rdname measures
measureRMSE = function(truth, response) {
sqrt(measureMSE(truth, response))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
medse = makeMeasure(
id = "medse", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Median of squared errors",
note = "Defined as: median((response - truth)^2).",
fun = function(task, model, pred, feats, extra.args) {
measureMEDSE(pred$data$truth, pred$data$response)
}
)
#' @export measureMEDSE
#' @rdname measures
measureMEDSE = function(truth, response) {
median((response - truth)^2)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
sae = makeMeasure(
id = "sae", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Sum of absolute errors",
note = "Defined as: sum(abs(response - truth))",
fun = function(task, model, pred, feats, extra.args) {
measureSAE(pred$data$truth, pred$data$response)
}
)
#' @export measureSAE
#' @rdname measures
measureSAE = function(truth, response) {
sum(abs(response - truth))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mae = makeMeasure(
id = "mae", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Mean of absolute errors",
note = "Defined as: mean(abs(response - truth))",
fun = function(task, model, pred, feats, extra.args) {
measureMAE(pred$data$truth, pred$data$response)
}
)
#' @export measureMAE
#' @rdname measures
measureMAE = function(truth, response) {
mean(abs(response - truth))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
medae = makeMeasure(
id = "medae", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Median of absolute errors",
note = "Defined as: median(abs(response - truth)).",
fun = function(task, model, pred, feats, extra.args) {
measureMEDAE(pred$data$truth, pred$data$response)
}
)
#' @export measureMEDAE
#' @rdname measures
measureMEDAE = function(truth, response) {
median(abs(response - truth))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
rsq = makeMeasure(
id = "rsq", minimize = FALSE, best = 1, worst = -Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Coefficient of determination",
note = "Also called R-squared, which is 1 - residual_sum_of_squares / total_sum_of_squares.",
fun = function(task, model, pred, feats, extra.args) {
measureRSQ(pred$data$truth, pred$data$response)
}
)
#' @export measureRSQ
#' @rdname measures
measureRSQ = function(truth, response) {
rss = measureSSE(truth, response)
ess = sum((truth - mean(truth))^2L)
if (ess == 0) {
warning("Measure is undefined if all truth values are equal.")
return(NA_real_)
}
1 - rss / ess
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
expvar = makeMeasure(
id = "expvar", minimize = FALSE, best = 1, worst = 0,
properties = c("regr", "req.pred", "req.truth"),
name = "Explained variance",
note = "Similar to measure rsq (R-squared). Defined as explained_sum_of_squares / total_sum_of_squares.",
fun = function(task, model, pred, feats, extra.args) {
measureEXPVAR(pred$data$truth, pred$data$response)
}
)
#' @export measureEXPVAR
#' @rdname measures
measureEXPVAR = function(truth, response) {
regss = sum((response - mean(truth))^2L)
ess = sum((truth - mean(truth))^2L)
if (ess == 0) {
warning("Measure is undefined if all truth values are equal.")
return(NA_real_)
}
regss / ess
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
rrse = makeMeasure(
id = "rrse", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Root relative squared error",
note = "Defined as sqrt (sum_of_squared_errors / total_sum_of_squares). Undefined for single instances and when every truth value is identical. In this case the output will be NA.",
fun = function(task, model, pred, feats, extra.args) {
measureRRSE(pred$data$truth, pred$data$response)
}
)
#' @export measureRRSE
#' @rdname measures
measureRRSE = function(truth, response) {
tss = sum((truth - mean(truth))^2L)
if (tss == 0) {
warning("Measure is undefined if all truth values are equal.")
return(NA_real_)
}
sqrt(measureSSE(truth, response) / tss)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
rae = makeMeasure(
id = "rae", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Relative absolute error",
note = "Defined as sum_of_absolute_errors / mean_absolute_deviation. Undefined for single instances and when every truth value is identical. In this case the output will be NA.",
fun = function(task, model, pred, feats, extra.args) {
measureRAE(pred$data$truth, pred$data$response)
}
)
#' @export measureRAE
#' @rdname measures
measureRAE = function(truth, response) {
meanad = sum(abs(truth - mean(truth)))
if (meanad == 0) {
warning("Measure is undefined if all truth values are equal.")
return(NA_real_)
}
return(measureSAE(truth, response) / meanad)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mape = makeMeasure(
id = "mape", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Mean absolute percentage error",
note = "Defined as the abs(truth_i - response_i) / truth_i. Won't work if any truth value is equal to zero. In this case the output will be NA.",
fun = function(task, model, pred, feats, extra.args) {
measureMAPE(pred$data$truth, pred$data$response)
}
)
#' @export measureMAPE
#' @rdname measures
measureMAPE = function(truth, response) {
if (any(truth == 0)) {
warning("Measure is undefined if any truth value is equal to 0.")
return(NA_real_)
}
return(mean(abs((truth - response) / truth)))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
msle = makeMeasure(
id = "msle", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Mean squared logarithmic error",
note = "Defined as: mean((log(response + 1, exp(1)) - log(truth + 1, exp(1)))^2).
This measure is mostly used for count data, note that all predicted and actual target values must be greater or equal '-1'
to compute the measure.",
fun = function(task, model, pred, feats, extra.args) {
measureMSLE(pred$data$truth, pred$data$response)
}
)
#' @export measureMSLE
#' @rdname measures
measureMSLE = function(truth, response) {
if (any(truth < -1)) {
stop("All truth values must be greater or equal -1")
}
if (any(response < -1)) {
stop("All predicted values must be greater or equal -1")
}
mean((log(response + 1) - log(truth + 1))^2)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
rmsle = makeMeasure(
id = "rmsle", minimize = TRUE, best = 0, worst = Inf,
properties = c("regr", "req.pred", "req.truth"),
name = "Root mean squared logarithmic error",
note = "Defined as: sqrt(msle). Definition taken from:
Definition taken from: https: / /www.kaggle.com / wiki / RootMeanSquaredLogarithmicError.
This measure is mostly used for count data, note that all predicted and actual target values
must be greater or equal '-1' to compute the measure.",
fun = function(task, model, pred, feats, extra.args) {
measureRMSLE(pred$data$truth, pred$data$response)
}
)
#' @export measureRMSLE
#' @rdname measures
measureRMSLE = function(truth, response) {
sqrt(measureMSLE(truth, response))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
kendalltau = makeMeasure(
id = "kendalltau", minimize = FALSE, best = 1, worst = -1,
properties = c("regr", "req.pred", "req.truth"),
name = "Kendall's tau",
note = "Defined as: Kendall's tau correlation between truth and response. Only looks at the order.
See Rosset et al.: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.95.1398&rep=rep1&type=pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureKendallTau(pred$data$truth, pred$data$response)
}
)
#' @export measureKendallTau
#' @rdname measures
measureKendallTau = function(truth, response) {
cor(truth, response, use = "na.or.complete", method = "kendall")
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
spearmanrho = makeMeasure(
id = "spearmanrho", minimize = FALSE, best = 1, worst = -1,
properties = c("regr", "req.pred", "req.truth"),
name = "Spearman's rho",
note = "Defined as: Spearman's rho correlation between truth and response. Only looks at the order.
See Rosset et al.: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.95.1398&rep=rep1&type=pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureSpearmanRho(pred$data$truth, pred$data$response)
}
)
#' @export measureSpearmanRho
#' @rdname measures
measureSpearmanRho = function(truth, response) {
cor(truth, response, use = "na.or.complete", method = "spearman")
}
###############################################################################
### classif multi ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mmce = makeMeasure(
id = "mmce", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Mean misclassification error",
note = "Defined as: mean(response != truth)",
fun = function(task, model, pred, feats, extra.args) {
measureMMCE(pred$data$truth, pred$data$response)
}
)
#' @export measureMMCE
#' @rdname measures
measureMMCE = function(truth, response) {
mean(response != truth)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
acc = makeMeasure(
id = "acc", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Accuracy",
note = "Defined as: mean(response == truth)",
fun = function(task, model, pred, feats, extra.args) {
measureACC(pred$data$truth, pred$data$response)
}
)
#' @export measureACC
#' @rdname measures
measureACC = function(truth, response) {
mean(response == truth)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
ber = makeMeasure(
id = "ber", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Balanced error rate",
note = "Mean of misclassification error rates on all individual classes.",
fun = function(task, model, pred, feats, extra.args) {
measureBER(pred$data$truth, pred$data$response)
}
)
#' @export measureBER
#' @rdname measures
measureBER = function(truth, response) {
# special case for predictions from FailureModel
if (anyMissing(response)) {
return(NA_real_)
}
mean(diag(1 - (table(truth, response) / table(truth, truth))))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multiclass.aunu = makeMeasure(
id = "multiclass.aunu", minimize = FALSE, best = 1, worst = 0.5,
properties = c("classif", "classif.multi", "req.pred", "req.truth", "req.prob"),
name = "Average 1 vs. rest multiclass AUC",
note = "Computes the AUC treating a c-dimensional classifier as c two-dimensional classifiers, where classes are assumed to have uniform distribution, in order to have a measure which is independent of class distribution change. See Ferri et al.: https://www.math.ucdavis.edu/~saito/data/roc/ferri-class-perf-metrics.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureAUNU(getPredictionProbabilities(pred, pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureAUNU
#' @rdname measures
measureAUNU = function(probabilities, truth) {
if (length(unique(truth)) != nlevels(truth)) {
warning("Measure is undefined if there isn't at least one sample per class.")
return(NA_real_)
}
mean(vnapply(1:nlevels(truth), function(i) colAUC(probabilities[, i], truth == levels(truth)[i])))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multiclass.aunp = makeMeasure(
id = "multiclass.aunp", minimize = FALSE, best = 1, worst = 0.5,
properties = c("classif", "classif.multi", "req.pred", "req.truth", "req.prob"),
name = "Weighted average 1 vs. rest multiclass AUC",
note = "Computes the AUC treating a c-dimensional classifier as c two-dimensional classifiers, taking into account the prior probability of each class. See Ferri et al.: https://www.math.ucdavis.edu/~saito/data/roc/ferri-class-perf-metrics.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureAUNP(getPredictionProbabilities(pred, pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureAUNP
#' @rdname measures
measureAUNP = function(probabilities, truth) {
if (length(unique(truth)) != nlevels(truth)) {
warning("Measure is undefined if there isn't at least one sample per class.")
return(NA_real_)
}
sum(vnapply(1:nlevels(truth), function(i) mean(truth == levels(truth)[i]) * colAUC(probabilities[, i], truth == levels(truth)[i])))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multiclass.au1u = makeMeasure(
id = "multiclass.au1u", minimize = FALSE, best = 1, worst = 0.5,
properties = c("classif", "classif.multi", "req.pred", "req.truth", "req.prob"),
name = "Average 1 vs. 1 multiclass AUC",
note = "Computes AUC of c(c - 1) binary classifiers (all possible pairwise combinations) while considering uniform distribution of the classes. See Ferri et al.: https://www.math.ucdavis.edu/~saito/data/roc/ferri-class-perf-metrics.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureAU1U(getPredictionProbabilities(pred, pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureAU1U
#' @rdname measures
measureAU1U = function(probabilities, truth) {
m = colAUC(probabilities, truth)
c = c(combn(1:nlevels(truth), 2))
mean(m[cbind(rep(seq_len(nrow(m)), each = 2), c)])
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multiclass.au1p = makeMeasure(
id = "multiclass.au1p", minimize = FALSE, best = 1, worst = 0.5,
properties = c("classif", "classif.multi", "req.pred", "req.truth", "req.prob"),
name = "Weighted average 1 vs. 1 multiclass AUC",
note = "Computes AUC of c(c - 1) binary classifiers while considering the a priori distribution of the classes. See Ferri et al.: https://www.math.ucdavis.edu/~saito/data/roc/ferri-class-perf-metrics.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureAU1P(getPredictionProbabilities(pred, pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureAU1P
#' @rdname measures
measureAU1P = function(probabilities, truth) {
m = colAUC(probabilities, truth)
weights = table(truth) / length(truth)
m = m * matrix(rep(weights, each = nrow(m)), ncol = length(weights))
c = c(combn(1:nlevels(truth), 2))
sum(m[cbind(rep(seq_len(nrow(m)), each = 2), c)]) / (nlevels(truth) - 1)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multiclass.brier = makeMeasure(
id = "multiclass.brier", minimize = TRUE, best = 0, worst = 2,
properties = c("classif", "classif.multi", "req.pred", "req.truth", "req.prob"),
name = "Multiclass Brier score",
note = "Defined as: (1/n) sum_i sum_j (y_ij - p_ij)^2, where y_ij = 1 if observation i has class j (else 0), and p_ij is the predicted probability of observation i for class j. From http://docs.lib.noaa.gov/rescue/mwr/078/mwr-078-01-0001.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureMulticlassBrier(getPredictionProbabilities(pred, pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureMulticlassBrier
#' @rdname measures
measureMulticlassBrier = function(probabilities, truth) {
truth = factor(truth, levels = colnames(probabilities))
mat01 = createDummyFeatures(truth)
mean(rowSums((probabilities - mat01)^2))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
logloss = makeMeasure(
id = "logloss", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "classif.multi", "req.truth", "req.prob"),
name = "Logarithmic loss",
note = "Defined as: -mean(log(p_i)), where p_i is the predicted probability of the true class of observation i. Inspired by https://www.kaggle.com/wiki/MultiClassLogLoss.",
fun = function(task, model, pred, feats, extra.args) {
measureLogloss(getPredictionProbabilities(pred, cl = pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureLogloss
#' @rdname measures
measureLogloss = function(probabilities, truth) {
eps = 1e-15
# let's confine the predicted probabilities to [eps,1 - eps], so logLoss doesn't reach infinity under any circumstance
probabilities[probabilities > 1 - eps] = 1 - eps
probabilities[probabilities < eps] = eps
truth = match(as.character(truth), colnames(probabilities))
p = getRowEls(probabilities, truth)
-1 * mean(log(p))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
ssr = makeMeasure(
id = "ssr", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "classif.multi", "req.truth", "req.prob"),
name = "Spherical Scoring Rule",
note = "Defined as: mean(p_i(sum_j(p_ij))), where p_i is the predicted probability of the true class of observation i and p_ij is the predicted probablity of observation i for class j.
See: Bickel, J. E. (2007). Some comparisons among quadratic, spherical, and logarithmic scoring rules. Decision Analysis, 4(2), 49-65.",
fun = function(task, model, pred, feats, extra.args) {
measureSSR(getPredictionProbabilities(pred, cl = pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureSSR
#' @rdname measures
measureSSR = function(probabilities, truth) {
truth = match(as.character(truth), colnames(probabilities))
p = getRowEls(probabilities, truth)
mean(p / sqrt(rowSums(probabilities^2)))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
qsr = makeMeasure(
id = "qsr", minimize = FALSE, best = 1, worst = -1,
properties = c("classif", "classif.multi", "req.truth", "req.prob"),
name = "Quadratic Scoring Rule",
note = "Defined as: 1 - (1/n) sum_i sum_j (y_ij - p_ij)^2, where y_ij = 1 if observation i has class j (else 0), and p_ij is the predicted probablity of observation i for class j.
This scoring rule is the same as 1 - multiclass.brier.
See: Bickel, J. E. (2007). Some comparisons among quadratic, spherical, and logarithmic scoring rules. Decision Analysis, 4(2), 49-65.",
fun = function(task, model, pred, feats, extra.args) {
measureQSR(getPredictionProbabilities(pred, cl = pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureQSR
#' @rdname measures
measureQSR = function(probabilities, truth) {
# We add this line because binary tasks only output one probability column
if (is.null(dim(probabilities))) probabilities = cbind(probabilities, 1 - probabilities)
truth = factor(truth, levels = colnames(probabilities))
1 - mean(rowSums((probabilities - createDummyFeatures(truth))^2))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
lsr = makeMeasure(
id = "lsr", minimize = FALSE, best = 0, worst = -Inf,
properties = c("classif", "classif.multi", "req.truth", "req.prob"),
name = "Logarithmic Scoring Rule",
note = "Defined as: mean(log(p_i)), where p_i is the predicted probability of the true class of observation i.
This scoring rule is the same as the negative logloss, self-information or surprisal.
See: Bickel, J. E. (2007). Some comparisons among quadratic, spherical, and logarithmic scoring rules. Decision Analysis, 4(2), 49-65.",
fun = function(task, model, pred, feats, extra.args) {
measureLSR(getPredictionProbabilities(pred, cl = pred$task.desc$class.levels), pred$data$truth)
}
)
#' @export measureLSR
#' @rdname measures
measureLSR = function(probabilities, truth) {
-1 * measureLogloss(probabilities, truth)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
kappa = makeMeasure(
id = "kappa", minimize = FALSE, best = 1, worst = -1,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Cohen's kappa",
note = "Defined as: 1 - (1 - p0) / (1 - pe). With: p0 = 'observed frequency of
agreement' and pe = 'expected agremeent frequency under independence",
fun = function(task, model, pred, feats, extra.args) {
measureKAPPA(pred$data$truth, pred$data$response)
}
)
#' @export measureKAPPA
#' @rdname measures
measureKAPPA = function(truth, response) {
# get confusion matrix
conf.mat = table(truth, response)
conf.mat = conf.mat / sum(conf.mat)
# observed agreement frequency
p0 = sum(diag(conf.mat))
# get expected probs under independence
rowsum = rowSums(conf.mat)
colsum = colSums(conf.mat)
pe = sum(rowsum * colsum) / sum(conf.mat)^2
# calculate kappa
1 - (1 - p0) / (1 - pe)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
wkappa = makeMeasure(
id = "wkappa", minimize = FALSE, best = 1, worst = -1,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Mean quadratic weighted kappa",
note = "Defined as: 1 - sum(weights * conf.mat) / sum(weights * expected.mat),
the weight matrix measures seriousness of disagreement with the squared euclidean metric.",
fun = function(task, model, pred, feats, extra.args) {
measureWKAPPA(pred$data$truth, pred$data$response)
}
)
#' @export measureWKAPPA
#' @rdname measures
measureWKAPPA = function(truth, response) {
# get confusion matrix
conf.mat = table(truth, response)
conf.mat = conf.mat / sum(conf.mat)
# get expected probs under independence
rowsum = rowSums(conf.mat)
colsum = colSums(conf.mat)
expected.mat = rowsum %*% t(colsum)
# get weights
class.values = seq_along(levels(truth)) - 1L
weights = outer(class.values, class.values, FUN = function(x, y) (x - y)^2)
# calculate weighted kappa
1 - sum(weights * conf.mat) / sum(weights * expected.mat)
}
###############################################################################
### classif binary ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
auc = makeMeasure(
id = "auc", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth", "req.prob"),
name = "Area under the curve",
note = "Integral over the graph that results from computing fpr and tpr for many different thresholds.",
fun = function(task, model, pred, feats, extra.args) {
if (anyMissing(pred$data$response) || length(unique(pred$data$truth)) == 1L) {
return(NA_real_)
}
measureAUC(getPredictionProbabilities(pred), pred$data$truth, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureAUC
#' @rdname measures
measureAUC = function(probabilities, truth, negative, positive) {
if (is.factor(truth)) {
i = as.integer(truth) == which(levels(truth) == positive)
} else {
i = truth == positive
}
if (length(unique(i)) < 2L) {
stop("truth vector must have at least two classes")
}
# Use fast ranking function from data.table for larger vectors
if (length(i) > 5000L) {
r = frankv(probabilities)
} else {
r = rank(probabilities)
}
n.pos = as.numeric(sum(i))
n.neg = length(i) - n.pos
(sum(r[i]) - n.pos * (n.pos + 1) / 2) / (n.pos * n.neg)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
brier = makeMeasure(
id = "brier", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "req.pred", "req.truth", "req.prob"),
name = "Brier score",
note = "The Brier score is defined as the quadratic difference between the probability and the value (1,0) for the class.
That means we use the numeric representation 1 and 0 for our target classes. It is similiar to the mean squared error in regression.
multiclass.brier is the sum over all one vs. all comparisons and for a binary classifcation 2 * brier.",
fun = function(task, model, pred, feats, extra.args) {
measureBrier(getPredictionProbabilities(pred), pred$data$truth, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureBrier
#' @rdname measures
measureBrier = function(probabilities, truth, negative, positive) {
y = as.numeric(truth == positive)
mean((y - probabilities)^2)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
brier.scaled = makeMeasure(
id = "brier.scaled", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth", "req.prob"),
name = "Brier scaled",
note = "Brier score scaled to [0,1], see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3575184/.",
fun = function(task, model, pred, feats, extra.args) {
measureBrierScaled(getPredictionProbabilities(pred), pred$data$truth, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureBrierScaled
#' @rdname measures
measureBrierScaled = function(probabilities, truth, negative, positive) {
y = as.numeric(truth == positive)
brier = mean((y - probabilities)^2)
inc = mean(probabilities)
brier.max = inc * (1 - inc)^2 + (1 - inc) * inc^2
1 - brier / brier.max
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
bac = makeMeasure(
id = "bac", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "classif.multi", "req.pred", "req.truth"),
name = "Balanced accuracy",
note = "For binary tasks, mean of true positive rate and true negative rate.",
fun = function(task, model, pred, feats, extra.args) {
measureBAC(pred$data$truth, pred$data$response)
}
)
#' @export measureBAC
#' @rdname measures
measureBAC = function(truth, response) {
mean(diag(table(truth, response) / table(truth, truth)))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
tp = makeMeasure(
id = "tp", minimize = FALSE, best = Inf, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "True positives",
note = "Sum of all correctly classified observations in the positive class.",
fun = function(task, model, pred, feats, extra.args) {
measureTP(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureTP
#' @rdname measures
measureTP = function(truth, response, positive) {
sum(truth == response & response == positive)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
tn = makeMeasure(
id = "tn", minimize = FALSE, best = Inf, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "True negatives",
note = "Sum of correctly classified observations in the negative class. Also called correct rejections.",
fun = function(task, model, pred, feats, extra.args) {
measureTN(pred$data$truth, pred$data$response, pred$task.desc$negative)
}
)
#' @export measureTN
#' @rdname measures
measureTN = function(truth, response, negative) {
sum(truth == response & response == negative)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
fp = makeMeasure(
id = "fp", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "req.pred", "req.truth"),
name = "False positives",
note = "Sum of misclassified observations in the positive class. Also called false alarms.",
fun = function(task, model, pred, feats, extra.args) {
measureFP(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureFP
#' @rdname measures
measureFP = function(truth, response, positive) {
sum(truth != response & response == positive)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
fn = makeMeasure(
id = "fn", minimize = TRUE, best = 0, worst = Inf,
properties = c("classif", "req.pred", "req.truth"),
name = "False negatives",
note = "Sum of misclassified observations in the negative class. Also called misses.",
fun = function(task, model, pred, feats, extra.args) {
measureFN(pred$data$truth, pred$data$response, pred$task.desc$negative)
}
)
#' @export measureFN
#' @rdname measures
measureFN = function(truth, response, negative) {
sum(truth != response & response == negative)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
tpr = makeMeasure(
id = "tpr", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "True positive rate",
note = "Percentage of correctly classified observations in the positive class. Also called hit rate or recall or sensitivity.",
fun = function(task, model, pred, feats, extra.args) {
measureTPR(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureTPR
#' @rdname measures
measureTPR = function(truth, response, positive) {
measureTP(truth, response, positive) / sum(truth == positive)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
tnr = makeMeasure(
id = "tnr", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "True negative rate",
note = "Percentage of correctly classified observations in the negative class. Also called specificity.",
fun = function(task, model, pred, feats, extra.args) {
measureTNR(pred$data$truth, pred$data$response, pred$task.desc$negative)
}
)
#' @export measureTNR
#' @rdname measures
measureTNR = function(truth, response, negative) {
measureTN(truth, response, negative) / sum(truth == negative)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
fpr = makeMeasure(
id = "fpr", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "req.pred", "req.truth"),
name = "False positive rate",
note = "Percentage of misclassified observations in the positive class. Also called false alarm rate or fall-out.",
fun = function(task, model, pred, feats, extra.args) {
measureFPR(pred$data$truth, pred$data$response, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureFPR
#' @rdname measures
measureFPR = function(truth, response, negative, positive) {
measureFP(truth, response, positive) / sum(truth == negative)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
fnr = makeMeasure(
id = "fnr", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "req.pred", "req.truth"),
name = "False negative rate",
note = "Percentage of misclassified observations in the negative class.",
fun = function(task, model, pred, feats, extra.args) {
measureFNR(pred$data$truth, pred$data$response, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureFNR
#' @rdname measures
measureFNR = function(truth, response, negative, positive) {
measureFN(truth, response, negative) / sum(truth == positive)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
ppv = makeMeasure(
id = "ppv", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "Positive predictive value",
note = "Defined as: tp / (tp + fp). Also called precision. If the denominator is 0, PPV is set to be either 1 or 0 depending on whether the highest probability prediction is positive (1) or negative (0).",
fun = function(task, model, pred, feats, extra.args) {
if (pred$predict.type == "prob") {
prob = getPredictionProbabilities(pred)
} else {
prob = NULL
}
measurePPV(pred$data$truth, pred$data$response, pred$task.desc$positive, prob)
}
)
#' @export measurePPV
#' @rdname measures
measurePPV = function(truth, response, positive, probabilities = NULL) {
denominator = sum(response == positive)
ifelse(denominator == 0, measureEdgeCase(truth, positive, probabilities), measureTP(truth, response, positive) / denominator)
}
measureEdgeCase = function(truth, positive, prob) {
if (!is.null(prob)) {
rs = sort(prob, index.return = TRUE)
erst = ifelse(truth[getLast(rs$ix)] == positive, 1, 0)
} else {
erst = NA
}
erst
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
npv = makeMeasure(
id = "npv", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "Negative predictive value",
note = "Defined as: tn / (tn + fn).",
fun = function(task, model, pred, feats, extra.args) {
measureNPV(pred$data$truth, pred$data$response, pred$task.desc$negative)
}
)
#' @export measureNPV
#' @rdname measures
measureNPV = function(truth, response, negative) {
measureTN(truth, response, negative) / sum(response == negative)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
fdr = makeMeasure(
id = "fdr", minimize = TRUE, best = 0, worst = 1,
properties = c("classif", "req.pred", "req.truth"),
name = "False discovery rate",
note = "Defined as: fp / (tp + fp).",
fun = function(task, model, pred, feats, extra.args) {
measureFDR(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureFDR
#' @rdname measures
measureFDR = function(truth, response, positive) {
measureFP(truth, response, positive) / sum(response == positive)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mcc = makeMeasure(
id = "mcc", minimize = FALSE,
properties = c("classif", "req.pred", "req.truth"), best = 1, worst = -1,
name = "Matthews correlation coefficient",
note = "Defined as (tp * tn - fp * fn) / sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)), denominator set to 1 if 0",
fun = function(task, model, pred, feats, extra.args) {
measureMCC(pred$data$truth, pred$data$response, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureMCC
#' @rdname measures
measureMCC = function(truth, response, negative, positive) {
tn = as.numeric(measureTN(truth, response, negative))
tp = as.numeric(measureTP(truth, response, positive))
fn = as.numeric(measureFN(truth, response, negative))
fp = as.numeric(measureFP(truth, response, positive))
denom = sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
# According to Wikipedia, the denominator can be set arbitrarily if it's 0. 1 seems to make as much sense as anything else.
if (denom == 0) denom = 1
(tp * tn - fp * fn) / denom
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
f1 = makeMeasure(
id = "f1", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "F1 measure",
note = "Defined as: 2 * tp/ (sum(truth == positive) + sum(response == positive))",
fun = function(task, model, pred, feats, extra.args) {
measureF1(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureF1
#' @rdname measures
measureF1 = function(truth, response, positive) {
2 * measureTP(truth, response, positive) /
(sum(truth == positive) + sum(response == positive))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
gmean = makeMeasure(
id = "gmean", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "G-mean",
note = "Geometric mean of recall and specificity.",
fun = function(task, model, pred, feats, extra.args) {
measureGMEAN(pred$data$truth, pred$data$response, pred$task.desc$negative, pred$task.desc$positive)
}
)
#' @export measureGMEAN
#' @rdname measures
#' @references
#' He, H. & Garcia, E. A. (2009)
#' *Learning from Imbalanced Data.*
#' IEEE Transactions on Knowledge and Data Engineering, vol. 21, no. 9. pp. 1263-1284.
measureGMEAN = function(truth, response, negative, positive) {
sqrt(measureTPR(truth, response, positive) * measureTNR(truth, response, negative))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
gpr = makeMeasure(
id = "gpr", minimize = FALSE, best = 1, worst = 0,
properties = c("classif", "req.pred", "req.truth"),
name = "Geometric mean of precision and recall.",
note = "Defined as: sqrt(ppv * tpr)",
fun = function(task, model, pred, feats, extra.args) {
measureGPR(pred$data$truth, pred$data$response, pred$task.desc$positive)
}
)
#' @export measureGPR
#' @rdname measures
measureGPR = function(truth, response, positive) {
sqrt(measurePPV(truth, response, positive) * measureTPR(truth, response, positive))
}
###############################################################################
### multilabel ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.hamloss = makeMeasure(
id = "multilabel.hamloss", minimize = TRUE, best = 0, worst = 1,
properties = c("multilabel", "req.pred", "req.truth"),
name = "Hamming loss",
note = "Proportion of labels that are predicted incorrectly, following the definition
by Charte and Charte: https://journal.r-project.org/archive/2015-2/charte-charte.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelHamloss(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelHamloss
#' @rdname measures
measureMultilabelHamloss = function(truth, response) {
mean(truth != response)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.subset01 = makeMeasure(
id = "multilabel.subset01", minimize = TRUE, best = 0, worst = 1,
properties = c("multilabel", "req.pred", "req.truth"),
name = "Subset-0-1 loss",
note = "Proportion of observations where the complete multilabel set (all 0-1-labels) is predicted incorrectly,
following the definition by Charte and Charte: https://journal.r-project.org/archive/2015-2/charte-charte.pdf.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelSubset01(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelSubset01
#' @rdname measures
measureMultilabelSubset01 = function(truth, response) {
mean(!apply(truth == response, 1, all))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.f1 = makeMeasure(
id = "multilabel.f1", minimize = FALSE, best = 1, worst = 0,
properties = c("multilabel", "req.pred", "req.truth"),
name = "F1 measure (multilabel)",
note = "Harmonic mean of precision and recall on a per instance basis (Micro-F1), following the
definition by Montanes et al.: http: / /www.sciencedirect.com / science / article / pii / S0031320313004019.
Fractions where the denominator becomes 0 are replaced with 1 before computing the average across all instances.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelF1(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelF1
#' @rdname measures
measureMultilabelF1 = function(truth, response) {
numerator = 2 * rowSums(truth & response)
denominator = rowSums(truth + response)
mean(ifelse(denominator == 0, 1, numerator / denominator))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.acc = makeMeasure(
id = "multilabel.acc", minimize = FALSE, best = 1, worst = 0,
properties = c("multilabel", "req.pred", "req.truth"),
name = "Accuracy (multilabel)",
note = "Averaged proportion of correctly predicted labels with respect to the total number of labels for each instance,
following the definition by Charte and Charte: https: / /journal.r-project.org / archive / 2015 - 2 / charte-charte.pdf.
Fractions where the denominator becomes 0 are replaced with 1 before computing the average across all instances.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelACC(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelACC
#' @rdname measures
measureMultilabelACC = function(truth, response) {
numerator = rowSums(truth & response)
denominator = rowSums(truth | response)
mean(ifelse(denominator == 0, 1, numerator / denominator))
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.ppv = makeMeasure(
id = "multilabel.ppv", minimize = FALSE, best = 1, worst = 0,
properties = c("multilabel", "req.pred", "req.truth"),
name = "Positive predictive value (multilabel)",
note = "Also called precision. Averaged ratio of correctly predicted labels for each instance,
following the definition by Charte and Charte: https: / /journal.r-project.org / archive / 2015 - 2 / charte-charte.pdf.
Fractions where the denominator becomes 0 are ignored in the average calculation.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelPPV(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelPPV
#' @rdname measures
measureMultilabelPPV = function(truth, response) {
numerator = rowSums(truth & response)
denominator = rowSums(response)
mean(numerator / denominator, na.rm = TRUE)
}
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
multilabel.tpr = makeMeasure(
id = "multilabel.tpr", minimize = FALSE, best = 1, worst = 0,
properties = c("multilabel", "req.pred", "req.truth"),
name = "TPR (multilabel)",
note = "Also called recall. Averaged proportion of predicted labels which are relevant for each instance,
following the definition by Charte and Charte: https: / /journal.r-project.org / archive / 2015 - 2 / charte-charte.pdf.
Fractions where the denominator becomes 0 are ignored in the average calculation.",
fun = function(task, model, pred, feats, extra.args) {
measureMultilabelTPR(
getPredictionTruth.PredictionMultilabel(pred),
getPredictionResponse.PredictionMultilabel(pred))
}
)
#' @export measureMultilabelTPR
#' @rdname measures
measureMultilabelTPR = function(truth, response) {
numerator = rowSums(truth & response)
denominator = rowSums(truth)
mean(numerator / denominator, na.rm = TRUE)
}
###############################################################################
### survival ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
cindex = makeMeasure(
id = "cindex", minimize = FALSE, best = 1, worst = 0,
properties = c("surv", "req.pred", "req.truth"),
name = "Harrell's Concordance index",
note = "Fraction of all pairs of subjects whose predicted survival times are correctly ordered among all subjects that can actually be ordered. In other words, it is the probability of concordance between the predicted and the observed survival.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("_Hmisc")
y = getPredictionResponse(pred)
if (anyMissing(y)) {
return(NA_real_)
}
s = getPredictionTruth(pred)
Hmisc::rcorr.cens(-1 * y, s)[["C Index"]]
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
#' @references
#' H. Uno et al.
#' *On the C-statistics for Evaluating Overall Adequacy of Risk Prediction Procedures with Censored Survival Data*
#' Statistics in medicine. 2011;30(10):1105-1117. \doi{10.1002/sim.4154}.
cindex.uno = makeMeasure(
id = "cindex.uno", minimize = FALSE, best = 1, worst = 0,
properties = c("surv", "req.pred", "req.truth", "req.model", "req.task"),
name = "Uno's Concordance index",
note = "Fraction of all pairs of subjects whose predicted survival times are correctly ordered among all subjects that can actually be ordered. In other words, it is the probability of concordance between the predicted and the observed survival. Corrected by weighting with IPCW as suggested by Uno. Implemented in survAUC::UnoC.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("_survAUC")
y = getPredictionResponse(pred)
if (anyMissing(y)) {
return(NA_real_)
}
surv.train = getTaskTargets(task, recode.target = "surv")[model$subset]
max.time = assertNumber(extra.args$max.time, null.ok = TRUE) %??% max(getTaskTargets(task)[, 1L])
survAUC::UnoC(Surv.rsp = surv.train, Surv.rsp.new = getPredictionTruth(pred), time = max.time, lpnew = y)
},
extra.args = list(max.time = NULL)
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
#' @references
#' H. Uno et al.
#' *Evaluating Prediction Rules for T-Year Survivors with Censored Regression Models*
#' Journal of the American Statistical Association 102, no. 478 (2007): 527-37.
iauc.uno = makeMeasure(
id = "iauc.uno", minimize = FALSE, best = 1, worst = 0,
properties = c("surv", "req.pred", "req.truth", "req.model", "req.task"),
name = "Uno's estimator of cumulative AUC for right censored time-to-event data",
note = "To set an upper time limit, set argument max.time (defaults to max time in complete task). Implemented in survAUC::AUC.uno.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("_survAUC")
max.time = assertNumber(extra.args$max.time, null.ok = TRUE) %??% max(getTaskTargets(task)[, 1L])
times = seq(from = 0, to = max.time, length.out = extra.args$resolution)
surv.train = getTaskTargets(task, recode.target = "surv")[model$subset]
y = getPredictionResponse(pred)
if (anyMissing(y)) {
return(NA_real_)
}
survAUC::AUC.uno(Surv.rsp = surv.train, Surv.rsp.new = getPredictionTruth(pred), times = times, lpnew = y)$iauc
},
extra.args = list(max.time = NULL, resolution = 1000L)
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
ibrier = makeMeasure(
id = "ibrier", minimize = TRUE, best = 0, worst = 1,
properties = c("surv", "req.truth", "req.model", "req.task"),
name = "Integrated brier score using Kaplan-Meier estimator for weighting",
note = "Only works for methods for which probabilities are provided via pec::predictSurvProb. Currently these are only coxph and randomForestSRC. To set an upper time limit, set argument max.time (defaults to max time in test data). Implemented in pec::pec",
fun = function(task, model, pred, feats, extra.args) {
requirePackages(c("survival", "pec"))
targets = getTaskTargets(task)
tn = getTaskTargetNames(task)
f = as.formula(sprintf("Surv(%s, %s) ~ 1", tn[1L], tn[2L]))
newdata = getTaskData(task)[model$subset, ]
max.time = extra.args$max.time %??% max(newdata[[tn[1L]]])
grid = seq(0, max.time, length.out = extra.args$resolution)
probs = predictSurvProb(getLearnerModel(model, more.unwrap = TRUE), newdata = newdata, times = grid)
perror = pec(probs, f,
data = newdata[, tn, with = FALSE], times = grid, exact = FALSE, exactness = 99L,
maxtime = max.time, verbose = FALSE, reference = FALSE)
crps(perror, times = max.time)[[1]]
},
extra.args = list(max.time = NULL, resolution = 1000L)
)
###############################################################################
### cost-sensitive ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
meancosts = makeMeasure(
id = "meancosts", minimize = TRUE, best = 0, worst = Inf,
properties = c("costsens", "req.pred", "req.task"),
name = "Mean costs of the predicted choices",
note = "Defined as: mean(y), where y is the vector of costs for the predicted classes.",
fun = function(task, model, pred, feats, extra.args) {
classes = as.character(pred$data$response)
ids = pred$data$id
costs = getTaskCosts(task)
y = mapply(function(id, cl) {
costs[id, cl]
}, ids, classes, SIMPLIFY = TRUE, USE.NAMES = FALSE)
mean(y)
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
mcp = makeMeasure(
id = "mcp", minimize = TRUE, best = 0, worst = Inf,
properties = c("costsens", "req.pred", "req.task"),
name = "Misclassification penalty",
note = "Average difference between costs of oracle and model prediction.",
fun = function(task, model, pred, feats, extra.args) {
mc = meancosts$fun(task, NULL, pred, NULL, extra.args)
oc = mean(apply(getTaskCosts(task), 1L, min))
mc - oc
}
)
###############################################################################
### clustering ###
###############################################################################
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
db = makeMeasure(
id = "db", minimize = TRUE, best = 0, worst = Inf,
properties = c("cluster", "req.pred", "req.feats"),
name = "Davies-Bouldin cluster separation measure",
note = "Ratio of the within cluster scatter, to the between cluster separation, averaged over the clusters. See `?clusterSim::index.DB`.",
fun = function(task, model, pred, feats, extra.args) {
if (length(unique(pred$data$response)) > 1L) {
requirePackages("clusterSim", default.method = "load")
r = as.integer(as.factor(pred$data$response))
clusterSim::index.DB(feats, r)$DB
} else {
NA
}
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
G1 = makeMeasure(
id = "G1", minimize = FALSE, best = Inf, worst = 0, # nolint
properties = c("cluster", "req.pred", "req.feats"),
name = "Calinski-Harabasz pseudo F statistic",
note = "Defined as ratio of between-cluster variance to within cluster variance. See `?clusterSim::index.G1`.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("clusterSim", default.method = "load")
r = as.integer(as.factor(pred$data$response))
clusterSim::index.G1(feats, r)
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
G2 = makeMeasure(
id = "G2", minimize = FALSE, best = 1, worst = 0, # nolint
properties = c("cluster", "req.pred", "req.feats"),
name = "Baker and Hubert adaptation of Goodman-Kruskal's gamma statistic",
note = "Defined as: (number of concordant comparisons - number of discordant comparisons) / (number of concordant comparisons + number of discordant comparisons). See `?clusterSim::index.G2`.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("clusterSim", default.method = "load")
r = as.integer(as.factor(pred$data$response))
clusterSim::index.G2(clusterSim::dist.GDM(feats), r)
}
)
#' @export
#' @format NULL
#' @usage NULL
#' @rdname measures
silhouette = makeMeasure(
id = "silhouette", minimize = FALSE, best = Inf, worst = 0,
properties = c("cluster", "req.pred", "req.feats"),
name = "Rousseeuw's silhouette internal cluster quality index",
note = "Silhouette value of an observation is a measure of how similar an object is to its own cluster compared to other clusters. The measure is calculated as the average of all silhouette values. See `?clusterSim::index.S`.",
fun = function(task, model, pred, feats, extra.args) {
requirePackages("clusterSim", default.method = "load")
r = as.integer(as.factor(pred$data$response))
clusterSim::index.S(clusterSim::dist.GDM(feats), r)
}
)
|