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
|
// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
//
#include <BALL/QSAR/classificationValidation.h>
#include <BALL/QSAR/statistics.h>
#include <BALL/QSAR/classificationModel.h>
#include <BALL/QSAR/registry.h>
#include <boost/random/mersenne_twister.hpp>
using namespace std;
namespace BALL
{
namespace QSAR
{
ClassificationValidation::ClassificationValidation(ClassificationModel* m) : Validation(m)
{
clas_model = m; quality_ = -1; quality_cv_ = -1; quality_input_test_ = -1;
qualCalculation = &ClassificationValidation::calculateAverageSensitivity;
}
void ClassificationValidation::selectStat(int s)
{
if (s >= 0 && s <= 4)
{
validation_statistic_ = s;
}
if (s == 0)
{
qualCalculation = &ClassificationValidation::calculateAverageSensitivity;
}
else if (s == 1)
{
qualCalculation = &ClassificationValidation::calculateWeightedSensitivity;
}
else if (s == 2)
{
qualCalculation = &ClassificationValidation::calculateOverallAccuracy;
}
else if (s == 3)
{
qualCalculation = &ClassificationValidation::calculateAverageMCC;
}
else if (s == 4)
{
qualCalculation = &ClassificationValidation::calculateOverallMCC;
}
else if (s == 5)
{
qualCalculation = &ClassificationValidation::calculateTDR;
}
}
void ClassificationValidation::crossValidation(int k, bool restore)
{
if (model_->data->descriptor_matrix_.size() == 0 || model_->data->Y_.size() == 0)
{
throw Exception::InconsistentUsage(__FILE__, __LINE__, "Data must be fetched from input-files by QSARData before cross-validation can be done!");
}
Eigen::MatrixXd desc_backup;
//Eigen::MatrixXd res_backup;
Eigen::MatrixXd y_backup;
if (restore)
{
desc_backup = model_->descriptor_matrix_; // save matrices in order in restore them after cross-validation
//res_backup = clas_model->training_result_;
y_backup = model_->Y_;
}
int lines = model_->data->descriptor_matrix_[0].size();
int col = model_->data->descriptor_matrix_.size();
if (!model_->descriptor_IDs_.empty())
{
col = model_->descriptor_IDs_.size();
}
double average_accuracy = 0;
class_results_.resize(clas_model->labels_.size());
class_results_.setZero();
// test k times
for (int i = 0; i < k; i++)
{
int test_size = (lines+i)/k;
int training_size = lines-test_size;
model_->Y_.resize(training_size, model_->data->Y_.size());
model_->descriptor_matrix_.resize(training_size, col);
test_substances_.resize(test_size);
test_Y_.resize(test_size, model_->data->Y_.size());
int train_line = 0; // no of line in descriptor_matrix_ of model_
int test_line = 0;
//copy data to training and test data set
for (int line = 0; line < lines; line++)
{
if ((line+1+i)%k == 0)
{
setTestLine(test_line, line);
test_line++;
}
else
{
setTrainingLine(train_line, line);
train_line++;
}
}
// test Model with model_->predict() for each line of test-data
model_->train();
testAllSubstances(0); // do not transform cross-validation test-data again...
average_accuracy += quality_;
}
quality_cv_ = average_accuracy/k;
class_results_ = class_results_/k;
if (restore)
{
model_->descriptor_matrix_ = desc_backup; // prevent confusion of cross-validation coefficients with coefficients
model_->Y_ = y_backup;
model_->readTrainingData();
model_->train();
}
}
void ClassificationValidation::testAllSubstances(bool transform)
{
confusion_matrix_.resize(4, clas_model->labels_.size());
confusion_matrix_.setZero();
class_results_.resize(clas_model->labels_.size());
class_results_.setZero();
for (int i = 0; i < (int)test_substances_.size(); i++) // for all substances in test-data
{
Eigen::VectorXd rv = model_->predict(test_substances_[i], transform);
for (int c = 0; c < test_Y_.cols(); c++) // for all modelled activities
{
int y_ic = static_cast<int>(test_Y_(i, c));
int rv_ic = static_cast<int>(rv(c));
for (int k = 0; k < confusion_matrix_.cols(); k++) // set TP, FP, TN, FN for all classes
{
if ((clas_model->labels_)[k] == y_ic)
{
if (y_ic == rv_ic)
{
confusion_matrix_(0, k)++; // TP for class k
}
else
{
confusion_matrix_(3, k)++; // FN for class k
}
}
else
{
if (clas_model->labels_[k] != rv_ic)
{
confusion_matrix_(2, k)++; // TN for class k
}
else
{
confusion_matrix_(1, k)++; // FP for class k
}
}
}
}
}
(this->*qualCalculation)();
}
void ClassificationValidation::testInputData(bool transform)
{
int lines = model_->data->descriptor_matrix_[0].size();
test_substances_.resize(lines);
test_Y_.resize(lines, model_->data->Y_.size());
class_results_.resize(clas_model->labels_.size());
class_results_.setZero();
bool back_transform = 0;
if (transform && model_->data->descriptor_transformations_.size() > 0)
{
// if test data is to be transformed according to centering of training data, BUT has already been centered itself
back_transform = 1;
}
for (int i = 0; i < lines; i++)
{
setTestLine(i, i, back_transform);
}
testAllSubstances(transform);
quality_input_test_ = quality_;
}
void ClassificationValidation::bootstrap(int k, bool restore)
{
if (model_->data->descriptor_matrix_.size() == 0 || model_->data->Y_.size() == 0)
{
throw Exception::InconsistentUsage(__FILE__, __LINE__, "Data must be fetched from input-files by QSARData before bootstrapping can be done!");
}
Eigen::MatrixXd desc_backup;
Eigen::MatrixXd res_backup;
Eigen::MatrixXd y_backup;
if (restore)
{
desc_backup = model_->descriptor_matrix_; // save matrices in order in restore them after cross-validation
//res_backup = clas_model->training_result_;
y_backup = model_->Y_;
}
class_results_.resize(clas_model->labels_.size());
class_results_.setZero();
quality_cv_ = 0;
int N = model_->data->descriptor_matrix_[0].size();
int no_descriptors = model_->data->descriptor_matrix_.size();
if (!model_->descriptor_IDs_.empty())
{
no_descriptors = model_->descriptor_IDs_.size();
}
boost::mt19937 rng(PreciseTime::now().getMicroSeconds());
double overall_fit = 0;
double overall_pred = 0;
Eigen::VectorXd class_results_pred;
class_results_pred.resize(clas_model->labels_.size()); class_results_pred.setZero();
Eigen::VectorXd class_results_fit;
class_results_fit.resize(clas_model->labels_.size()); class_results_fit.setZero();
for (int i = 0; i < k; i++) // create and evaluate k bootstrap samples
{
vector<int> sample_substances(N, 0); // numbers of occurences of substances within this sample
class_results_.setZero();
/// create training matrix and train the model_
model_->descriptor_matrix_.resize(N, no_descriptors);
model_->Y_.resize(N, model_->data->Y_.size());
for (int j = 0; j < N; j++)
{
//int pos = rand()%N;
int pos = rng() % N;
setTrainingLine(j, pos);
sample_substances[pos]++;
}
model_->train();
/// find size of test data set
int test_size = 0;
for (int j = 0; j < N; j++)
{
if (sample_substances[j] > 0)
{
continue;
}
test_size++;
}
test_substances_.resize(test_size);
test_Y_.resize(test_size, model_->data->Y_.size());
/// create test data set and calculate quality_ of prediction
int test_line = 0;
for (int j = 0; j < N; j++)
{
if (sample_substances[j] == 0)
{
setTestLine(test_line, j);
test_line++;
}
}
testAllSubstances(0);
overall_pred += quality_;
class_results_pred += class_results_;
class_results_.setZero(); // clear pred. result before adding training fit result!!
/// create test data set and calculate quality_ of fit to training data
test_substances_.resize(N);
test_Y_.resize(N, model_->data->Y_.size());
test_line = 0;
for (int j = 0; j < N; j++)
{
while (sample_substances[j] > 0) // insert substance as often as it occurs in the training data set
{
setTestLine(test_line, j);
test_line++;
sample_substances[j]--;
}
}
testAllSubstances(0);
overall_fit += quality_;
class_results_fit += class_results_;
}
overall_pred = overall_pred/k;
overall_fit = overall_fit/k;
class_results_pred = class_results_pred/k;
class_results_fit = class_results_fit/k;
quality_cv_ = 0.632*overall_pred + 0.368*overall_fit;
class_results_ = class_results_pred*0.632 + class_results_fit*0.368;
if (restore)
{
model_->descriptor_matrix_ = desc_backup; // prevent confusion of cross-validation coefficients with coefficients
model_->Y_ = y_backup;
model_->readTrainingData();
model_->train();
}
}
const Eigen::MatrixXd & ClassificationValidation::yRandomizationTest(int runs, int k)
{
Eigen::MatrixXd y_backup = model_->Y_;
Eigen::MatrixXd desc_backup = model_->descriptor_matrix_;
//Eigen::MatrixXd res_backup = clas_model->training_result_;
VMatrix dataY_backup = model_->data->Y_;
//Eigen::VectorXd c(2, -1);
//vector<Eigen::VectorXd > results(runs, 2);
yRand_results_.resize(runs, 2);
yRand_results_.fill(-1);
class_results_.resize(clas_model->labels_.size());
class_results_.setZero();
for (int i = 0; i < runs; i++)
{
yRand(); // randomize all columns of Y_
crossValidation(k, 0);
testInputData(0);
yRand_results_(i, 0) = quality_input_test_;
yRand_results_(i, 1) = quality_cv_;
}
class_results_ = class_results_/runs;
model_->Y_ = y_backup;
model_->descriptor_matrix_ = desc_backup;
//clas_model->training_result_ = res_backup;
QSARData* data = const_cast <QSARData*> (model_->data);
data->Y_ = dataY_backup;
model_->train();
return yRand_results_;
}
void ClassificationValidation::calculateOverallAccuracy()
{
// do NOT calculate accuracy seperately for each class!
int TP = 0;
for (int j = 0; j < confusion_matrix_.cols(); j++)
{
TP += (int)confusion_matrix_(0, j);
}
int N = 0; // number of predictions
for (int j = 0; j < confusion_matrix_.rows(); j++)
{
N += (int)confusion_matrix_(j, 0);
}
quality_ = ((double)TP) / N;
}
void ClassificationValidation::calculateAverageSensitivity()
{
quality_ = 0;
for (int j = 0; j < confusion_matrix_.cols(); j++) // calculate quality_ of all classes
{
int TP = (int)confusion_matrix_(0, j);
int FN = (int)confusion_matrix_(3, j);
double sens = 1;
if (TP != 0 || FN != 0)
{
sens = ((double)TP) / (TP+FN);
}
class_results_(j) += sens;
quality_ += sens;
}
quality_ /= confusion_matrix_.cols(); // mean quality_ of all classes
}
void ClassificationValidation::calculateWeightedSensitivity()
{
quality_ = 0;
int no_all = 0;
// get number of substances that were used for training the model_
for (int i = 0; i < (int)clas_model->no_substances_.size(); i++)
{
no_all += clas_model->no_substances_[i];
}
for (int j = 0; j < confusion_matrix_.cols(); j++)
{
int TP = (int)confusion_matrix_(0, j);
int FN = (int)confusion_matrix_(3, j);
double sens = 1;
if (TP != 0 || FN != 0)
{
sens = ((double)TP) / (TP+FN);
}
double sens_weighted = sens*(((double)clas_model->no_substances_[j])/no_all);
class_results_(j) += sens_weighted;
quality_ += sens_weighted;
}
}
void ClassificationValidation::calculateAverageMCC()
{
quality_ = 0;
double MCC = 0;
for (int j = 0; j < confusion_matrix_.cols(); j++)
{
int TP = (int)confusion_matrix_(0, j);
int FP = (int)confusion_matrix_(1, j);
int TN = (int)confusion_matrix_(2, j);
int FN = (int)confusion_matrix_(3, j);
double nom = ((double)TP)*TN-FP*FN; // (often) too big for int...
double denom = ((double)(TP+FP))*(TP+FN)*(TN+FP)*(TN+FN);
if (denom != 0) denom = sqrt(denom);
else denom = 1;
double d = nom/denom;
class_results_(j) += d;
MCC += d;
}
quality_ = MCC/confusion_matrix_.cols();
}
void ClassificationValidation::calculateOverallMCC()
{
quality_ = 0;
int TP = 0; int FP = 0; int TN = 0; int FN = 0;
for (int j = 0; j < confusion_matrix_.cols(); j++)
{
TP += (int)confusion_matrix_(0, j);
FP += (int)confusion_matrix_(1, j);
TN += (int)confusion_matrix_(2, j);
FN += (int)confusion_matrix_(3, j);
}
double nom = ((double)TP)*TN-FP*FN; // (often) too big for int...
double denom = ((double)(TP+FP))*(TP+FN)*(TN+FP)*(TN+FN);
if (denom != 0) denom = sqrt(denom);
else denom = 1;
quality_ = nom/denom;
}
// calculation of True Discovery Rate
void ClassificationValidation::calculateTDR()
{
quality_ = 0;
int TP = 0; int FP = 0;
if (confusion_matrix_.cols() > 2)
{
throw BALL::Exception::GeneralException(__FILE__, __LINE__, "Classification validation error", "True Discovery Rate can only be calculated for binary classification data sets!");
}
TP = (int)confusion_matrix_(0, 1);
FP = (int)confusion_matrix_(1, 1);
if (TP == 0)
{
quality_ = 0;
return;
}
quality_ = ((double)TP)/(TP+FP);
}
const Eigen::MatrixXd* ClassificationValidation::getConfusionMatrix()
{
return &confusion_matrix_;
}
const Eigen::VectorXd* ClassificationValidation::getClassResults()
{
return &class_results_;
}
double ClassificationValidation::getAccuracyInputTest()
{
return quality_input_test_;
}
double ClassificationValidation::getAccuracyCV()
{
return quality_cv_;
}
double ClassificationValidation::getCVRes()
{
return quality_cv_;
}
void ClassificationValidation::setCVRes(double d)
{
quality_cv_ = d;
}
double ClassificationValidation::getFitRes()
{
return quality_input_test_;
}
void ClassificationValidation::saveToFile(string filename) const
{
saveToFile(filename, quality_input_test_, quality_cv_);
}
void ClassificationValidation::saveToFile(string filename, const double& quality_input_test, const double& predictive_quality) const
{
ofstream out(filename.c_str());
Registry reg;
out<<"# used quality statistic: "<<reg.getClassificationStatisticName(validation_statistic_)<<endl<<endl;
out << "Fit to training data = "<<quality_input_test<<endl;
out << "Predictive quality = "<<predictive_quality<<endl;
}
void ClassificationValidation::readFromFile(string filename)
{
ifstream in(filename.c_str());
while (in)
{
String line;
getline(in, line);
line.trimLeft();
if(line=="" || line.hasPrefix("#") || line.hasPrefix("//") || line.hasPrefix("%"))
{
continue;
}
if (line.hasPrefix("Fit to training data"))
{
quality_input_test_ = ((String)line.after("=")).trimLeft().toDouble();
}
else if (line.hasPrefix("Predictive quality"))
{
quality_cv_ = ((String)line.after("=")).trimLeft().toDouble();
}
}
}
}
}
|