Evaluator.cpp 43.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/gserver/evaluators/Evaluator.h"
Y
Yu Yang 已提交
16
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
17 18 19

#include "paddle/gserver/gradientmachines/NeuralNetwork.h"

20
DECLARE_int32(trainer_id);
Z
zhangjinchao01 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34

namespace paddle {

void Evaluator::eval(const NeuralNetwork& nn) {
  std::vector<Argument> arguments;
  arguments.reserve(config_.input_layers_size());
  for (const std::string& name : config_.input_layers()) {
    arguments.push_back(nn.getLayer(name)->getOutput());
  }
  SetDevice device(arguments[0].deviceId);
  real score = evalImp(arguments);
  totalScore_ += score;
  updateSamplesNum(arguments);
}
Q
qijun 已提交
35 36 37 38 39
/**
 * @brief classification error Evaluator
 *
 * The config file api is classification_error_evaluator.
 */
Z
zhangjinchao01 已提交
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
class ClassificationErrorEvaluator : public Evaluator {
public:
  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {
    if (3 == arguments.size()) {
      numSamples_ += arguments[2].value->getSum();
    } else {
      numSamples_ += arguments[0].getBatchSize();
    }
  }

  MatrixPtr calcError(std::vector<Argument>& arguments) {
    CHECK_GE(arguments.size(), (size_t)2);
    CHECK_LE(arguments.size(), (size_t)3);
    MatrixPtr& output = arguments[0].value;
    IVectorPtr& label = arguments[1].ids;
    MatrixPtr& multiBinaryLabel = arguments[1].value;  // For multi binary label
    bool supportWeight = (3 == arguments.size()) ? true : false;
    MatrixPtr weight = supportWeight ? arguments[2].value : nullptr;
    if (nullptr == output ||
        (nullptr == label && nullptr == multiBinaryLabel) ||
        (supportWeight && nullptr == weight)) {
      return 0;
    }

    if (label != nullptr) {
      CHECK_EQ(label->getSize(), output->getHeight());
    } else {
      CHECK_EQ(multiBinaryLabel->getHeight(), output->getHeight());
      CHECK_EQ(multiBinaryLabel->getWidth(), output->getWidth());
    }
    if (supportWeight) {
      CHECK_EQ(output->getHeight(), weight->getHeight());
      CHECK_EQ((size_t)1, weight->getWidth());
    }

    const MatrixPtr errorMat = Matrix::create(output->getHeight(),
76 77 78
                                              1,
                                              /* trans= */ false,
                                              useGpu(arguments[0].deviceId));
Z
zhangjinchao01 已提交
79 80
    errorMat->zeroMem();
    if (label != nullptr) {
81
      errorMat->classificationError(*output, *label);
Z
zhangjinchao01 已提交
82 83
    } else if (dynamic_cast<CpuSparseMatrix*>(multiBinaryLabel.get()) ||
               dynamic_cast<GpuSparseMatrix*>(multiBinaryLabel.get())) {
84 85
      errorMat->classificationErrorMulti(
          *output, *multiBinaryLabel, config_.classification_threshold());
Z
zhangjinchao01 已提交
86
    } else {
87 88
      errorMat->binaryClassificationError(
          0, *output, *multiBinaryLabel, config_.classification_threshold());
Z
zhangjinchao01 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    }

    if (supportWeight) {
      errorMat->dotMul(*errorMat, *weight);
    }
    return errorMat;
  }

  virtual real evalImp(std::vector<Argument>& arguments) {
    MatrixPtr errorMat = calcError(arguments);
    return errorMat->getSum();
  }

  virtual void distributeEval(ParameterClient2* client) {
    mergeResultsOfAllClients(client);
  }
};

Q
qijun 已提交
107 108 109 110 111
/**
 * @brief sequence classification error Evaluator
 * @note sequence level classification error stats,
 * if any frame in one sequence has error, the sequence is error
 */
Z
zhangjinchao01 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
class SequenceClassificationErrorEvaluator
    : public ClassificationErrorEvaluator {
public:
  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {
    numSamples_ += arguments[0].getNumSequences();
  }

  virtual real evalImp(std::vector<Argument>& arguments) {
    auto sequenceStartPositions =
        arguments[0].sequenceStartPositions->getVector(false);
    CHECK(sequenceStartPositions != nullptr);
    const int* starts = sequenceStartPositions->getData();

    MatrixPtr errorMat = calcError(arguments);

    int errCounter = 0;
    CpuVector errorVec(0, nullptr);
    for (size_t i = 0; i < sequenceStartPositions->getSize() - 1; ++i) {
130 131
      errorVec.subVecFrom(
          errorMat->getData(), starts[i], starts[i + 1] - starts[i]);
Z
zhangjinchao01 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145
      if (errorVec.getSum() > 0) {
        errCounter += 1;
      }
    }

    return static_cast<real>(errCounter);
  }

  virtual void distributeEval(ParameterClient2* client) {
    mergeResultsOfAllClients(client);
  }
};
REGISTER_EVALUATOR(seq_classification_error,
                   SequenceClassificationErrorEvaluator);
Q
qijun 已提交
146 147 148 149 150 151
/**
 * @brief sum Evaluator
 * Calculate the sum of output or label
 *
 * The config file api is sum_evaluator.
 */
Z
zhangjinchao01 已提交
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
class SumEvaluator : public Evaluator {
public:
  SumEvaluator() : cpuLabel_(nullptr), cpuWeight_(nullptr) {}

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {
    if (2 == arguments.size()) {
      numSamples_ += arguments[1].value->getSum();
    } else {
      numSamples_ += arguments[0].getBatchSize();
    }
  }

  virtual real evalImp(std::vector<Argument>& arguments) {
    REGISTER_TIMER("SumEvaluator");
    CHECK_GE(arguments.size(), (size_t)1);
    CHECK_LE(arguments.size(), (size_t)2);
    bool supportWeight = (2 == arguments.size()) ? true : false;
    if (supportWeight) {
      if (nullptr == arguments[1].value) {
        return 0;
      }
      CHECK_EQ(arguments[1].value->getWidth(), (size_t)1);
    }

    // The sum of output
    if (arguments[0].value) {
      if (supportWeight) {
        CHECK_EQ(arguments[0].value->getHeight(),
                 arguments[1].value->getHeight());
        MatrixPtr tmpMat = Matrix::create(arguments[0].value->getHeight(),
                                          arguments[0].value->getWidth(),
                                          /* trans= */ false,
                                          arguments[0].value->useGpu());
        tmpMat->copyFrom(*arguments[0].value);
        tmpMat->rowScale(0, *tmpMat, *arguments[1].value);
        return tmpMat->getSum();
      } else {
        return arguments[0].value->getSum();
      }
      // The sum of label
    } else if (arguments[0].ids) {
      size_t insNum = arguments[0].ids->getSize();
      IVectorPtr label = arguments[0].ids;
      MatrixPtr weight = supportWeight ? arguments[1].value : nullptr;
      if (dynamic_cast<GpuIVector*>(label.get())) {
        IVector::resizeOrCreate(cpuLabel_, insNum, false);
        cpuLabel_->copyFrom(*arguments[0].ids);

        if (supportWeight) {
          CHECK_EQ(insNum, arguments[1].value->getHeight());
          Matrix::resizeOrCreate(cpuWeight_, insNum, (size_t)1, false, false);
          cpuWeight_->copyFrom(*arguments[1].value);
        }

        label = cpuLabel_;
        weight = cpuWeight_;
      }

      if (supportWeight) {
        real score = 0.0;
        int* labelD = label->getData();
        real* weightD = weight->getData();
        for (size_t i = 0; i < insNum; ++i) {
          score += (labelD[i] * weightD[i]);
        }
        return score;
      } else {
        return label->getSum();
      }
    } else {
      return 0;
    }
  }

  virtual void distributeEval(ParameterClient2* client) {
    mergeResultsOfAllClients(client);
  }

private:
  IVectorPtr cpuLabel_;
  MatrixPtr cpuWeight_;
};
Q
qijun 已提交
234 235 236 237 238 239 240 241 242 243
/**
 * @brief column sum Evaluator
 * @note column sum for the colIdx-th column *
 * - colIdx = 0: the 0-th column.
 * - colIdx > 0: the colIdx-th column.
 * - colIdx < 0: the last colIdx-th column.
 *
 * The config file api is column_sum_evaluator.
 *
 */
Z
zhangjinchao01 已提交
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
class ColumnSumEvaluator : public Evaluator {
public:
  explicit ColumnSumEvaluator(int32_t colIdx)
      : colIdx_(colIdx), colNum_(0), sum_(nullptr) {}

  virtual void start() {
    Evaluator::start();
    if (nullptr != sum_) {
      sum_->zeroMem();
    }
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {
    if (2 == arguments.size()) {
      numSamples_ += arguments[1].value->getSum();
    } else {
      numSamples_ += arguments[0].getBatchSize();
    }
  }

  virtual real evalImp(std::vector<Argument>& arguments) {
    REGISTER_TIMER("ColumnSumEvaluator");
    CHECK_GE(arguments.size(), (size_t)1);
    CHECK_LE(arguments.size(), (size_t)2);
    bool supportWeight = (2 == arguments.size()) ? true : false;
    if (nullptr == arguments[0].value ||
        (supportWeight && nullptr == arguments[1].value)) {
      return 0;
    }

    size_t insNum = arguments[0].value->getHeight();
    size_t colNum = arguments[0].value->getWidth();
    if (nullptr == sum_) {
      sum_ = Matrix::create((size_t)1, colNum, false, /* useGpu */ false);
      colNum_ = colNum;
      sum_->zeroMem();
    } else {
      CHECK_EQ(colNum, sum_->getWidth());
    }

    if (supportWeight) {
      CHECK_EQ(insNum, arguments[1].value->getHeight());
      CHECK_EQ((size_t)1, arguments[1].value->getWidth());
      MatrixPtr tmpMat = Matrix::create(insNum, colNum);
      if (arguments[0].value->useGpu()) {
        tmpMat->copyFrom(*arguments[0].value);
      }
      if (!arguments[1].value->useGpu()) {
        if (!arguments[0].value->useGpu()) {
          tmpMat->rowScale(0, *arguments[0].value, *arguments[1].value);
        } else {
          tmpMat->rowScale(0, *tmpMat, *arguments[1].value);
        }
      } else {
        MatrixPtr tmp2 = Matrix::create(insNum, 1);
        tmp2->copyFrom(*arguments[1].value);
        if (!arguments[0].value->useGpu()) {
          tmpMat->rowScale(0, *arguments[0].value, *tmp2);
        } else {
          tmpMat->rowScale(0, *tmpMat, *tmp2);
        }
      }
      sum_->accumulateColSum(*tmpMat);
    } else {
      if (!arguments[0].value->useGpu()) {
        sum_->accumulateColSum(*arguments[0].value);
      } else {
        MatrixPtr tmpMat = Matrix::create(insNum, colNum);
        tmpMat->copyFrom(*arguments[0].value);
        sum_->accumulateColSum(*tmpMat);
      }
    }
    return 0;
  }

Y
Yu Yang 已提交
319
  virtual void printStats(std::ostream& os) const {
Z
zhangjinchao01 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333
    CHECK(colIdx_ + (int32_t)colNum_ >= 0 && colIdx_ - (int32_t)colNum_ < 0)
        << "column index [" << colIdx_ << "] out of range [-" << colNum_ << ", "
        << colNum_ << ")";
    size_t colIdx = 0;
    if (colIdx_ >= 0) {
      colIdx = colIdx_;
    } else {
      colIdx = colNum_ + colIdx_;
    }
    os << config_.name() << "="
       << (numSamples_ ? sum_->getElement(0, colIdx) / numSamples_ : 0);
  }

  void distributeEval(ParameterClient2* client) {
334 335
    client->reduce(
        sum_->getData(), sum_->getData(), colNum_, FLAGS_trainer_id, 0);
Z
zhangjinchao01 已提交
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
    client->reduce(&numSamples_, &numSamples_, 1, FLAGS_trainer_id, 0);
  }

private:
  ColumnSumEvaluator() {}
  int32_t colIdx_;
  size_t colNum_;
  MatrixPtr sum_; /* cpu matrix */
};

void AucEvaluator::start() {
  Evaluator::start();
  memset(statPos_, 0, sizeof(statPos_));
  memset(statNeg_, 0, sizeof(statNeg_));
}

real AucEvaluator::evalImp(std::vector<Argument>& arguments) {
  REGISTER_TIMER("AucEvaluator");
  CHECK_GE(arguments.size(), (size_t)2);
  CHECK_LE(arguments.size(), (size_t)3);
  MatrixPtr output = arguments[0].value;
  IVectorPtr label = arguments[1].ids;
  bool supportWeight = (3 == arguments.size()) ? true : false;
  MatrixPtr weight = supportWeight ? arguments[2].value : nullptr;
  if (nullptr == output || nullptr == label ||
      (supportWeight && nullptr == weight)) {
    return 0;
  }
  size_t insNum = output->getHeight();
  size_t outputDim = output->getWidth();
  CHECK_EQ(insNum, label->getSize());
  if (supportWeight) {
    CHECK_EQ(insNum, weight->getHeight());
    CHECK_EQ((size_t)1, weight->getWidth());
  }

  CHECK(colIdx_ + (int32_t)outputDim >= 0 && colIdx_ - (int32_t)outputDim < 0)
      << "column index [" << colIdx_ << "] out of range [-" << outputDim << ", "
      << outputDim << ")";
  realColumnIdx_ = 0;
  if (colIdx_ >= 0) {
    realColumnIdx_ = colIdx_;
  } else {
    realColumnIdx_ = outputDim + colIdx_;
  }

  if (dynamic_cast<GpuMatrix*>(output.get())) {
383 384 385 386 387
    Matrix::resizeOrCreate(cpuOutput_,
                           insNum,
                           outputDim,
                           /* trans=*/false,
                           /* useGpu=*/false);
Z
zhangjinchao01 已提交
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
    cpuOutput_->copyFrom(*output);
    IVector::resizeOrCreate(cpuLabel_, insNum, false);
    cpuLabel_->copyFrom(*label);

    if (supportWeight) {
      Matrix::resizeOrCreate(cpuWeight_, insNum, (size_t)1, false, false);
      cpuWeight_->copyFrom(*weight);
    }

    output = cpuOutput_;
    label = cpuLabel_;
    weight = cpuWeight_;
  }

  real* outputD = output->getData();
  int* labelD = label->getData();
  real* weightD = supportWeight ? weight->getData() : nullptr;
  size_t pos = realColumnIdx_;
  for (size_t i = 0; i < insNum; ++i) {
    real value = outputD[pos];
    uint32_t binIdx = static_cast<uint32_t>(value * kBinNum_);
    CHECK(binIdx <= kBinNum_) << "bin index [" << binIdx
                              << "] out of range, predict value[" << value
                              << "]";
    real w = supportWeight ? weightD[i] : 1.0;
    if (labelD[i] == kNegativeLabel_) {
      statNeg_[binIdx] += w;
    } else {
      statPos_[binIdx] += w;
    }
    pos += outputDim;
  }
  return 0;
}

void AucEvaluator::distributeEval(ParameterClient2* client) {
  client->reduce(statPos_, statPos_, kBinNum_ + 1, FLAGS_trainer_id, 0);
  client->reduce(statNeg_, statNeg_, kBinNum_ + 1, FLAGS_trainer_id, 0);
}

Y
Yu Yang 已提交
428
double AucEvaluator::calcAuc() const {
Z
zhangjinchao01 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  double totPos = 0.0;
  double totNeg = 0.0;
  double totPosPrev = 0.0;
  double totNegPrev = 0.0;
  double auc = 0.0;

  int64_t idx = kBinNum_;
  while (idx >= 0) {
    totPosPrev = totPos;
    totNegPrev = totNeg;
    totPos += statPos_[idx];
    totNeg += statNeg_[idx];
    auc += trapezoidArea(totNeg, totNegPrev, totPos, totPosPrev);
    --idx;
  }

  if (totPos > 0.0 && totNeg > 0.0) {
    return auc / totPos / totNeg;
  } else {
    return 0.0;
  }
}

Y
Stash  
Yu Yang 已提交
452 453 454 455 456 457 458 459 460 461
real AucEvaluator::getValueImpl() const { return calcAuc(); }

std::string AucEvaluator::getTypeImpl() const {
  if (colIdx_ == -1) {
    return "last-column-auc";
  } else {
    return "auc";
  }
}

Z
zhangjinchao01 已提交
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
// class RankAucEvaluator
REGISTER_EVALUATOR(rankauc, RankAucEvaluator);

void RankAucEvaluator::start() { Evaluator::start(); }
void RankAucEvaluator::updateSamplesNum(
    const std::vector<Argument>& arguments) {
  numSamples_ += arguments[0].getNumSequences();
}
real RankAucEvaluator::evalImp(std::vector<Argument>& arguments) {
  CHECK_GE(arguments.size(), 2U);
  CHECK_LE(arguments.size(), 3U);
  double batchAuc = 0.0;
  output_ = arguments[0].value;
  click_ = arguments[1].value;
  size_t batchSize = output_->getHeight();
  CHECK(!output_->useGpu()) << "RankAUC evaluator does not support GPU!";

  if (arguments.size() == 3U) {
    pv_ = arguments[2].value;
  } else {
    Matrix::resizeOrCreate(pv_, batchSize, 1, false, false);
    std::fill(pv_->getData(), pv_->getData() + batchSize, 1.0);
  }

  real* outputData = output_->getData();
  real* clickData = click_->getData();
  real* pvData = pv_->getData();

  auto startPos = arguments[0].sequenceStartPositions->getVector(false);
  const int* startPosData = startPos->getData();
  size_t batchNum = startPos->getSize() - 1;
  for (size_t i = 0; i < batchNum; ++i) {
    int beginPos = startPosData[i];
    int endPos = startPosData[i + 1];
496 497 498 499
    batchAuc += calcRankAuc(outputData + beginPos,
                            clickData + beginPos,
                            pvData + beginPos,
                            endPos - beginPos);
Z
zhangjinchao01 已提交
500 501 502 503
  }
  return batchAuc;
}

504 505 506 507
double RankAucEvaluator::calcRankAuc(real* outputData,
                                     real* clickData,
                                     real* pvData,
                                     size_t size) {
Z
zhangjinchao01 已提交
508 509 510 511
  outputPair_.clear();
  for (size_t i = 0; i < size; ++i) {
    outputPair_.push_back(std::make_pair(outputData[i], i));
  }
512 513
  std::sort(outputPair_.begin(),
            outputPair_.end(),
Z
zhangjinchao01 已提交
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
            [](const std::pair<real, int>& a, const std::pair<real, int>& b) {
              return a.first > b.first;
            });
  double aucTmp = 0.0;
  double clickSum = 0.0;
  double oldClickSum = 0.0;
  double noClick = 0.0;
  double noClickSum = 0.0;

  double lastScore = outputPair_[0].first + 1.0;
  for (size_t i = 0; i < size; ++i) {
    if (lastScore != outputPair_[i].first) {
      aucTmp += (clickSum + oldClickSum) * noClick / 2.0;
      oldClickSum = clickSum;
      noClick = 0.0;
      lastScore = outputPair_[i].first;
    }
    size_t id = outputPair_[i].second;
    noClick += pvData[id] - clickData[id];
    noClickSum += noClick;
    clickSum += clickData[id];
  }
  aucTmp += (clickSum + oldClickSum) * noClick / 2.0;
  return (clickSum * noClickSum) == 0.0 ? 0.0
                                        : aucTmp / (clickSum * noClickSum);
}

Y
Yu Yang 已提交
541 542
std::string RankAucEvaluator::getTypeImpl() const { return "rankauc"; }

Z
zhangjinchao01 已提交
543 544 545 546 547 548
// class PrecisionRecallEvaluator
REGISTER_EVALUATOR(precision_recall, PrecisionRecallEvaluator);

void PrecisionRecallEvaluator::start() {
  Evaluator::start();
  statsInfo_.clear();
Y
Yu Yang 已提交
549
  values_.clear();
Z
zhangjinchao01 已提交
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
}

real PrecisionRecallEvaluator::evalImp(std::vector<Argument>& arguments) {
  REGISTER_TIMER("PrecisionRecallEvaluator");
  CHECK_GE(arguments.size(), (size_t)2);
  CHECK_LE(arguments.size(), (size_t)3);
  MatrixPtr output = arguments[0].value;
  IVectorPtr label = arguments[1].ids;
  MatrixPtr multiBinaryLabel = arguments[1].value;
  bool supportWeight = (3 == arguments.size()) ? true : false;
  MatrixPtr weight = supportWeight ? arguments[2].value : nullptr;
  if (nullptr == output || (nullptr == label && nullptr == multiBinaryLabel) ||
      (supportWeight && nullptr == weight)) {
    return 0;
  }

  size_t insNum = output->getHeight();
  size_t outputDim = output->getWidth();
  if (label != nullptr) {
    CHECK_EQ(insNum, label->getSize());
  } else {
    CHECK_EQ(insNum, multiBinaryLabel->getHeight());
    CHECK_EQ(outputDim, multiBinaryLabel->getWidth());
  }
  if (supportWeight) {
    CHECK_EQ(insNum, weight->getHeight());
    CHECK_EQ((size_t)1, weight->getWidth());
  }

  if (statsInfo_.size() != outputDim) {
    statsInfo_.clear();
    statsInfo_.resize(outputDim);
  }

  isMultiBinaryLabel_ = (nullptr == label) ? true : false;
  if (label != nullptr) {
    if (dynamic_cast<GpuMatrix*>(output.get())) {
      Matrix::resizeOrCreate(cpuOutput_, insNum, outputDim, false, false);
      cpuOutput_->copyFrom(*output);
      IVector::resizeOrCreate(cpuLabel_, insNum, false);
      cpuLabel_->copyFrom(*label);
      if (supportWeight) {
        Matrix::resizeOrCreate(cpuWeight_, insNum, (size_t)1, false, false);
        cpuWeight_->copyFrom(*weight);
      }

      output = cpuOutput_;
      label = cpuLabel_;
      weight = cpuWeight_;
    }
    calcStatsInfo(output, label, weight);
  } else {
    // Not support GPU for multi binary labels
    CHECK(dynamic_cast<CpuSparseMatrix*>(multiBinaryLabel.get()));
    calcStatsInfoMulti(output, multiBinaryLabel, weight);
  }
  return 0;
}

Y
Yu Yang 已提交
609 610 611
template <typename T1, typename T2>
void PrecisionRecallEvaluator::printStatsHelper(T1 labelCallback,
                                                T2 microAvgCallback) const {
Z
zhangjinchao01 已提交
612 613 614 615 616 617 618 619
  int label = config_.positive_label();
  if (label != -1) {
    CHECK(label >= 0 && label < (int)statsInfo_.size())
        << "positive_label [" << label << "] should be in range [0, "
        << statsInfo_.size() << ")";
    double precision =
        calcPrecision(statsInfo_[label].TP, statsInfo_[label].FP);
    double recall = calcRecall(statsInfo_[label].TP, statsInfo_[label].FN);
Y
Yu Yang 已提交
620
    labelCallback(label, precision, recall, calcF1Score(precision, recall));
Z
zhangjinchao01 已提交
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
    return;
  }

  // micro average method: precision = (TP1+TP2)/(TP1+FP1+TP2+FP2)
  // macro average method: precision = (precision1+precision2)/2
  double microTotalTP = 0;
  double microTotalFP = 0;
  double microTotalFN = 0;
  double macroAvgPrecision = 0;
  double macroAvgRecall = 0;
  size_t numLabels = statsInfo_.size();
  for (size_t i = 0; i < numLabels; ++i) {
    microTotalTP += statsInfo_[i].TP;
    microTotalFP += statsInfo_[i].FP;
    microTotalFN += statsInfo_[i].FN;
    macroAvgPrecision += calcPrecision(statsInfo_[i].TP, statsInfo_[i].FP);
    macroAvgRecall += calcRecall(statsInfo_[i].TP, statsInfo_[i].FN);
  }
  macroAvgPrecision /= numLabels;
  macroAvgRecall /= numLabels;
  double macroAvgF1Score = calcF1Score(macroAvgPrecision, macroAvgRecall);

  double microAvgPrecision = calcPrecision(microTotalTP, microTotalFP);
  double microAvgRecall = calcPrecision(microTotalTP, microTotalFN);
  double microAvgF1Score = calcF1Score(microAvgPrecision, microAvgRecall);
Y
Yu Yang 已提交
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

  microAvgCallback(macroAvgPrecision,
                   macroAvgRecall,
                   macroAvgF1Score,
                   isMultiBinaryLabel_,
                   microAvgPrecision,
                   microAvgRecall,
                   microAvgF1Score);
}

void PrecisionRecallEvaluator::printStats(std::ostream& os) const {
  this->printStatsHelper(
      [&os](int label, double precision, double recall, double f1) {
        os << "positive_label=" << label << " precision=" << precision
           << " recall=" << recall << " F1-score=" << f1;
      },
      [&os](double macroAvgPrecision,
            double macroAvgRecall,
            double macroAvgF1Score,
            bool isMultiBinaryLabel,
            double microAvgPrecision,
            double microAvgRecall,
            double microAvgF1Score) {
        os << "macro-average-precision=" << macroAvgPrecision
           << " macro-average-recall=" << macroAvgRecall
           << " macro-average-F1-score=" << macroAvgF1Score;
        if (!isMultiBinaryLabel) {
          // precision and recall are equal in this case
          os << " micro-average-precision=" << microAvgPrecision;
        } else {
          os << " micro-average-precision=" << microAvgPrecision
             << " micro-average-recall=" << microAvgRecall
             << " micro-average-F1-score=" << microAvgF1Score;
        }
      });
Z
zhangjinchao01 已提交
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
}

void PrecisionRecallEvaluator::calcStatsInfo(const MatrixPtr& output,
                                             const IVectorPtr& label,
                                             const MatrixPtr& weight) {
  size_t insNum = output->getHeight();
  size_t dim = output->getWidth();
  real* outputD = output->getData();
  int* labelD = label->getData();
  real* weightD = (weight != nullptr) ? weight->getData() : nullptr;
  for (size_t i = 0; i < insNum; ++i) {
    CHECK_GE(labelD[i], 0);
    CHECK_LT((size_t)labelD[i], dim);
    size_t maxIdx = 0;
    real maxValue = outputD[i * dim];
    for (size_t j = 1; j < dim; ++j) {
      size_t idx = i * dim + j;
      if (maxValue < outputD[idx]) {
        maxIdx = j;
        maxValue = outputD[idx];
      }
    }

    real w = (weightD != nullptr) ? weightD[i] : 1.0;
    if (maxIdx == (size_t)labelD[i]) {
      statsInfo_[maxIdx].TP += w;  // true positive for labelD[i]
      // true negative for all labels except for labelD[i]
      for (size_t j = 0; j < dim; ++j) {
        statsInfo_[j].TN += w;
      }
      statsInfo_[maxIdx].TN -= w;
    } else {
      statsInfo_[labelD[i]].FN += w;  // false negative for labelD[i]
      statsInfo_[maxIdx].FP += w;     // false positive for maxIdx
      // true negatives for all labels except for maxIdx and labelD[i]
      for (size_t j = 0; j < dim; ++j) {
        statsInfo_[j].TN += w;
      }
      statsInfo_[maxIdx].TN -= w;
      statsInfo_[labelD[i]].TN -= w;
    }
  }
}

void PrecisionRecallEvaluator::calcStatsInfoMulti(const MatrixPtr& output,
                                                  const MatrixPtr& label,
                                                  const MatrixPtr& weight) {
  size_t insNum = output->getHeight();
  size_t dim = output->getWidth();
  real* outputD = output->getData();
  auto labelD = dynamic_cast<CpuSparseMatrix*>(label.get());
  real* weightD = (weight != nullptr) ? weight->getData() : nullptr;
  real threshold = config_.classification_threshold();
  for (size_t i = 0; i < insNum; ++i) {
    for (size_t j = 0; j < dim; ++j) {
      real w = (weightD != nullptr) ? weightD[i] : 1.0;
      size_t idx = i * dim + j;
      if (outputD[idx] < threshold) {
        statsInfo_[j].TN += w;  // true negative
      } else {
        statsInfo_[j].FP += w;  // false positive
      }
    }

    const int* cols = labelD->getRowCols(i);
    for (size_t j = 0; j < labelD->getColNum(i); ++j) {
      CHECK_LT(size_t(cols[j]), dim);
      real w = (weightD != nullptr) ? weightD[i] : 1.0;
      size_t idx = i * dim + cols[j];
      if (outputD[idx] < threshold) {
        statsInfo_[cols[j]].FN += w;  // false negative
        statsInfo_[cols[j]].TN -= w;  // true negative
      } else {
        statsInfo_[cols[j]].TP += w;  // true positive
        statsInfo_[cols[j]].FP -= w;  // false positive
      }
    }
  }
}

Y
Yu Yang 已提交
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
void PrecisionRecallEvaluator::storeLocalValues() const {
  if (this->values_.size() == 0) {
    this->printStatsHelper(
        [this](int label, double precision, double recall, double f1) {
          values_["positive_label"] = (double)label;
          values_["precision"] = precision;
          values_["recal"] = recall;
          values_["F1-score"] = f1;
        },
        [this](double macroAvgPrecision,
               double macroAvgRecall,
               double macroAvgF1Score,
               bool isMultiBinaryLabel,
               double microAvgPrecision,
               double microAvgRecall,
               double microAvgF1Score) {
          values_["macro-average-precision"] = macroAvgPrecision;
          values_["macro-average-recall"] = macroAvgRecall;
          values_["macro-average-F1-score"] = macroAvgF1Score;
          if (!isMultiBinaryLabel) {
            // precision and recall are equal in this case
            values_["micro-average-precision"] = microAvgPrecision;
          } else {
            values_["micro-average-precision"] = microAvgPrecision;
            values_["micro-average-recall"] = microAvgRecall;
            values_["micro-average-F1-score"] = microAvgF1Score;
          }
        });
  }
}

void PrecisionRecallEvaluator::getNames(std::vector<std::string>* names) {
  this->storeLocalValues();
  names->clear();
  names->reserve(this->values_.size());
  for (auto it = this->values_.begin(); it != this->values_.end(); ++it) {
    names->push_back(this->config_.name() + "." + it->first);
  }
}

real PrecisionRecallEvaluator::getValue(const std::string& name,
                                        Error* err) const {
  this->storeLocalValues();
  auto it = this->values_.find(name);
  if (it != this->values_.end() && err != nullptr) {
    *err = Error("No such key %s", name.c_str());
    return .0f;
  }

  return it->second;
}

std::string PrecisionRecallEvaluator::getType(const std::string& name,
                                              Error* err) const {
  this->storeLocalValues();
  auto it = this->values_.find(name);
  if (it != this->values_.end() && err != nullptr) {
    *err = Error("No such key %s", name.c_str());
    return "";
  }
  return "precision_recall";
}

Z
zhangjinchao01 已提交
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
void PrecisionRecallEvaluator::distributeEval(ParameterClient2* client) {
  size_t size = 4 * statsInfo_.size();
  double* buf = new double[size];
  for (size_t i = 0; i < statsInfo_.size(); ++i) {
    buf[4 * i + 0] = statsInfo_[i].TP;
    buf[4 * i + 1] = statsInfo_[i].TN;
    buf[4 * i + 2] = statsInfo_[i].FP;
    buf[4 * i + 3] = statsInfo_[i].FN;
  }
  client->reduce(buf, buf, size, FLAGS_trainer_id, 0);
  for (size_t i = 0; i < statsInfo_.size(); ++i) {
    statsInfo_[i].TP = buf[4 * i + 0];
    statsInfo_[i].TN = buf[4 * i + 1];
    statsInfo_[i].FP = buf[4 * i + 2];
    statsInfo_[i].FN = buf[4 * i + 3];
  }
  delete[] buf;
}

REGISTER_EVALUATOR(pnpair, PnpairEvaluator);
void PnpairEvaluator::start() {
  Evaluator::start();
  memset(pairArray_, 0, sizeof(pairArray_));
  predictArray_.clear();
}

real PnpairEvaluator::evalImp(std::vector<Argument>& arguments) {
  CHECK_GE(arguments.size(), 3UL);
  CHECK_LE(arguments.size(), 4UL);
  MatrixPtr output = arguments[0].value;
  IVectorPtr label = arguments[1].ids;
  IVectorPtr info = arguments[2].ids;
  bool supportWeight = (4 == arguments.size()) ? true : false;
  MatrixPtr weight = supportWeight ? arguments[3].value : nullptr;
  if (nullptr == output || nullptr == label ||
      (supportWeight && nullptr == weight)) {
    return 0;
  }
  size_t height = output->getHeight();
  size_t width = output->getWidth();
  CHECK_EQ(height, label->getSize());
  CHECK_EQ(height, info->getSize());
  if (supportWeight) {
    CHECK_EQ(height, weight->getHeight());
    CHECK_EQ((size_t)1, weight->getWidth());
  }

  if (dynamic_cast<GpuMatrix*>(output.get())) {
    Matrix::resizeOrCreate(cpuOutput_, height, width, false, false);
    IVector::resizeOrCreate(cpuLabel_, height, false);
    IVector::resizeOrCreate(cpuInfo_, height, false);
    cpuOutput_->copyFrom(*output);
    cpuLabel_->copyFrom(*label);
    cpuInfo_->copyFrom(*info);

    output = cpuOutput_;
    label = cpuLabel_;
    info = cpuInfo_;

    if (supportWeight) {
      Matrix::resizeOrCreate(cpuWeight_, height, (size_t)1, false, false);
      cpuWeight_->copyFrom(*weight);
      weight = cpuWeight_;
    }
  }

  real* outputs = output->getData();
  int* labels = label->getData();
  int* infos = info->getData();
  real* weights = supportWeight ? weight->getData() : nullptr;
  for (size_t i = 0; i < output->getHeight(); i++) {
    real y1 = outputs[i * width + (width - 1)];
    real w = supportWeight ? weights[i] : 1.0;
    predictArray_.push_back(PredictionResult(y1, labels[i], infos[i], w));
  }
  return 0;
}

902 903 904 905 906 907
void PnpairEvaluator::stat(size_t start,
                           size_t end,
                           PredictionResult* answers,
                           double& pos,
                           double& neg,
                           double& spe) {
Z
zhangjinchao01 已提交
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
  for (size_t i = start; i < end; i++) {
    for (size_t j = i + 1; j < end; j++) {
      CHECK_EQ(answers[i].queryid, answers[j].queryid);
      // The pair weight is the mean of the two samples' weight
      double weight = (answers[i].weight + answers[j].weight) / 2.0;
      if (answers[i].label != answers[j].label) {
        if ((answers[i].out > answers[j].out &&
             answers[i].label > answers[j].label) ||
            (answers[i].out < answers[j].out &&
             answers[i].label < answers[j].label)) {
          pos += weight;
        } else if ((answers[i].out > answers[j].out &&
                    answers[i].label < answers[j].label) ||
                   (answers[i].out < answers[j].out &&
                    answers[i].label > answers[j].label)) {
          neg += weight;
        } else {
          spe += weight;
        }
      }
    }
  }
}

void PnpairEvaluator::calc(std::vector<PredictionResult>& predictArray) {
933 934
  std::sort(predictArray.begin(),
            predictArray.end(),
Z
zhangjinchao01 已提交
935 936 937 938 939 940 941 942 943 944
            [](const PredictionResult& x, const PredictionResult& y) {
              return x.queryid < y.queryid;
            });

  double pos = 0;
  double neg = 0;
  double special = 0;
  auto start = predictArray.begin();
  while (start != predictArray.end()) {
    auto end = std::find_if(
Y
Yu Yang 已提交
945 946 947
        start + 1, predictArray.end(), [=](const PredictionResult& x) {
          return x.queryid != start->queryid;
        });
Z
zhangjinchao01 已提交
948
    CHECK(end != start);
949 950 951 952 953 954
    stat(start - predictArray.begin(),
         end - predictArray.begin(),
         predictArray.data(),
         pos,
         neg,
         special);
Z
zhangjinchao01 已提交
955 956 957 958 959 960 961 962 963 964 965 966

    start = end;
  }

  pairArray_[0] += pos;
  pairArray_[1] += neg;

  LOG(INFO) << " calc total pos pair: " << pos
            << " calc total neg pair: " << neg
            << " calc total special pair: " << special;
}

Y
Yu Yang 已提交
967 968
std::string PnpairEvaluator::getTypeImpl() const { return "pnpair"; }

Z
zhangjinchao01 已提交
969 970
ClassRegistrar<Evaluator> Evaluator::registrar_;
Evaluator* Evaluator::create(const EvaluatorConfig& config) {
Y
Yu Yang 已提交
971
  Evaluator* evaluator = registrar_.createByType(config.type());
Z
zhangjinchao01 已提交
972 973 974
  evaluator->init(config);
  return evaluator;
}
Y
Yu Yang 已提交
975 976 977 978 979 980 981 982 983 984

REGISTER_EVALUATOR(classification_error, ClassificationErrorEvaluator);
REGISTER_EVALUATOR(sum, SumEvaluator);
static InitFunction __reg_type_auc_sum__([]() {
  Evaluator::registrar_.registerClass(
      "last-column-sum", [] { return new ColumnSumEvaluator(-1); });
  Evaluator::registrar_.registerClass("last-column-auc",
                                      [] { return new AucEvaluator(-1); });
});

Q
qijun 已提交
985 986 987 988 989
/**
 * @brief print value of each layer.
 *
 * The config file api is value_printer_evaluator.
 */
Z
zhangjinchao01 已提交
990 991 992 993 994 995
class ValuePrinter : public Evaluator {
public:
  ValuePrinter() {}

  virtual void eval(const NeuralNetwork& nn) {
    for (const std::string& name : config_.input_layers()) {
Y
Yu Yang 已提交
996 997 998 999 1000 1001
      std::vector<std::tuple<std::string, std::string>> out;
      auto err = nn.getLayerOutputValue(name, &out);
      err.check();
      for (auto& each : out) {
        LOG(INFO) << "layer=" << name << std::get<0>(each) << ":\n"
                  << std::get<1>(each);
Z
zhangjinchao01 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010
      }
    }
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) { return 0; }
};
REGISTER_EVALUATOR(value_printer, ValuePrinter);
Q
qijun 已提交
1011 1012 1013 1014 1015
/**
 * @brief print gradient of each layer.
 *
 * The config file api is gradient_printer_evaluator.
 */
Z
zhangjinchao01 已提交
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
class GradientPrinter : public Evaluator {
public:
  GradientPrinter() {}

  virtual void eval(const NeuralNetwork& nn) {
    for (const std::string& name : config_.input_layers()) {
      const Argument& argu = nn.getLayer(name)->getOutput();
      if (argu.grad) {
        std::ostringstream os;
        argu.grad->print(os);
        LOG(INFO) << "layer=" << name << " grad matrix:\n" << os.str();
      }
      if (auto startPos = argu.sequenceStartPositions) {
        std::ostringstream os;
        startPos->getVector(false)->print(os, startPos->getSize());
        LOG(INFO) << "layer=" << name << " sequence pos vector:\n" << os.str();
      }
    }
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) { return 0; }
};
REGISTER_EVALUATOR(gradient_printer, GradientPrinter);
Q
qijun 已提交
1041 1042 1043 1044 1045
/**
 * @brief print row max id vctor of each layer
 *
 * The config file api is maxid_printer_evaluator.
 */
Z
zhangjinchao01 已提交
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
class MaxIdPrinter : public Evaluator {
private:
  IVectorPtr maxIds_;
  MatrixPtr maxValues_;

public:
  MaxIdPrinter() {}

  virtual void eval(const NeuralNetwork& nn) {
    for (const std::string& name : config_.input_layers()) {
      const Argument& argu = nn.getLayer(name)->getOutput();
      if (argu.value) {
        size_t height = argu.value->getHeight();
        size_t width = config_.num_results();
        IVector::resizeOrCreate(maxIds_, height * width, false);
        Matrix::resizeOrCreate(maxValues_, height, width, false);
        argu.value->rowMax(*maxIds_, *maxValues_);
        std::ostringstream os;
        int* ids = maxIds_->getData();
        real* values = maxValues_->getData();
        for (size_t i = 0; i < height; ++i) {
          for (size_t j = 0; j < width; ++j) {
            size_t pos = i * width + j;
            os << ids[pos] << " : " << values[pos] << ", ";
          }
          os << std::endl;
        }
        LOG(INFO) << "layer=" << name << " row max id vector:\n" << os.str();
      }
    }
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) { return 0; }
};
REGISTER_EVALUATOR(max_id_printer, MaxIdPrinter);
Q
qijun 已提交
1083 1084 1085 1086 1087
/**
 * @brief print sequence max frames of each layer
 *
 * The config file api is maxframe_printer_evaluator.
 */
Z
zhangjinchao01 已提交
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
class MaxFramePrinter : public Evaluator {
private:
  IVectorPtr maxIds_;
  MatrixPtr maxValues_;
  MatrixPtr value_;

public:
  MaxFramePrinter() {
    value_ =
        Matrix::create(nullptr, /* height= */ 1, 1, /* trans= */ false, false);
  }

  virtual void eval(const NeuralNetwork& nn) {
    for (const std::string& name : config_.input_layers()) {
      const Argument& argu = nn.getLayer(name)->getOutput();

      CHECK_EQ(argu.value->getWidth(), 1LU);
      size_t numSequences = argu.getNumSequences();
      const int* starts = argu.sequenceStartPositions->getData(false);

      std::ostringstream os;
      for (size_t i = 0; i < numSequences; ++i) {
        size_t offset = starts[i];
        size_t size = starts[i + 1] - starts[i];
        value_->setData(argu.value->getData() + offset, 1LU, size);

        size_t height = 1LU;
        size_t width = std::min((size_t)config_.num_results(), size);
        IVector::resizeOrCreate(maxIds_, height * width, false);
        Matrix::resizeOrCreate(maxValues_, height, width, false);

        value_->rowMax(*maxIds_, *maxValues_);

        int* ids = maxIds_->getData();
        real* values = maxValues_->getData();
        for (size_t j = 0; j < width; ++j) {
          os << ids[j] << " : " << values[j] << ", ";
        }
        os << "total " << size << " frames" << std::endl;
      }
      LOG(INFO) << "layer=" << name << " sequence max frames:\n" << os.str();
    }
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) { return 0; }
};
REGISTER_EVALUATOR(max_frame_printer, MaxFramePrinter);

/**
Q
qijun 已提交
1139
 * @brief print text according to index matrix and a dictionary.
1140
 *
Q
qijun 已提交
1141 1142
 * There can be multiple input to this layer:
 * - If there is only one input, the input must be a matrix containing
Z
zhangjinchao01 已提交
1143
 *      the sequence of indices;
Q
qijun 已提交
1144
 * - If there are more than one input, the first input should be ids,
Z
zhangjinchao01 已提交
1145 1146 1147
 *      and are interpreted as sample ids.
 *
 * The output format will be:
1148
 *
Q
qijun 已提交
1149
 * - sequence without sub-sequence, and there is probability.
1150 1151
 *
 *     @code
Z
zhangjinchao01 已提交
1152
 *      id \t prob space_seperated_tokens_from_dictionary_according_to_seq
1153 1154
 *     @endcode
 *
Q
qijun 已提交
1155
 * - sequence without sub-sequence, and there is not probability.
1156 1157
 *
 *     @code
Z
zhangjinchao01 已提交
1158
 *      id \t space_seperated_tokens_from_dictionary_according_to_seq
1159 1160
 *     @endcode
 *
Q
qijun 已提交
1161
 * - sequence with sub-sequence, and there is not probability.
1162 1163
 *
 *     @code
Z
zhangjinchao01 已提交
1164 1165 1166
 *      id \t space_seperated_tokens_from_dictionary_according_to_sub_seq
 *      \t \t space_seperated_tokens_from_dictionary_according_to_sub_seq
 *      ...
1167
 *     @endcode
Z
zhangjinchao01 已提交
1168 1169 1170 1171
 *
 * Typically SequenceTextPrinter layer takes output of maxid or RecurrentGroup
 * with maxid (when generating) as an input.
 *
Q
qijun 已提交
1172 1173
 * The config file api is seqtext_printer_evaluator.
 *
Z
zhangjinchao01 已提交
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
 */
class SequenceTextPrinter : public Evaluator {
private:
  /// dict_file, which contains a list of tokens
  std::vector<std::string> dict_;
  /// result_file, which is the output file
  std::ofstream os_;
  /// True/False, to indicate whether to use space to separate output tokens.
  /// Default is True. No space is added if set to False.
  bool delimited_;
  /// store the cpu version of argument.ids
  std::vector<IVectorPtr> cpuIds_;
  /// store the probability associated with each sequence
  std::vector<MatrixPtr> cpuIn_;

public:
  SequenceTextPrinter() {}

  virtual void init(const EvaluatorConfig& config) {
    Evaluator::init(config);
    if (!config.dict_file().empty()) {
      loadFileList(config.dict_file(), dict_);
    }

    os_.open(config.result_file(), std::ofstream::trunc);
    CHECK(os_.is_open()) << "Failed to open file " << config.result_file();
    delimited_ = config.delimited();
  }

  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) {
    CHECK_GE(arguments.size(), 1LU);
    bool hasId = arguments.size() > 1;
    size_t numSequences = arguments[0].getNumSequences();
    if (hasId) {
      CHECK_EQ(arguments[0].ids->getSize(), numSequences)
          << "first input must be sample id.";
    }
    for (size_t i = hasId ? 1 : 0; i < arguments.size(); ++i) {
      CHECK_EQ((size_t)arguments[i].getNumSequences(), numSequences);
    }

    auto resizeVector = [](IVectorPtr& dest, const IVectorPtr& src) {
      if (src && src->useGpu()) {
        IVector::resizeOrCreate(dest, src->getSize(), false);
        dest->copyFrom(*src);
      } else {
        dest = src;
      }
    };

    auto resizeMatrix = [](MatrixPtr& dest, const MatrixPtr& src) {
      if (src && src->useGpu()) {
1228 1229
        Matrix::resizeOrCreate(
            dest, src->getHeight(), src->getWidth(), false, false);
Z
zhangjinchao01 已提交
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
        dest->copyFrom(*src);
      } else {
        dest = src;
      }
    };

    cpuIds_.resize(arguments.size());
    cpuIn_.resize(arguments.size());
    for (size_t i = 0; i < arguments.size(); ++i) {
      resizeVector(cpuIds_[i], arguments[i].ids);
      resizeMatrix(cpuIn_[i], arguments[i].in);
    }

    int* sampleIds = nullptr;
    if (hasId) {
      sampleIds = cpuIds_[0]->getData();
    }

    for (size_t i = 0; i < numSequences; ++i) {
      os_ << (hasId ? sampleIds[i] : i);
      for (size_t j = hasId ? 1 : 0; j < arguments.size(); ++j) {
        int* output = cpuIds_[j]->getData();
        const int* starts = arguments[j].sequenceStartPositions->getData(false);

        auto seqPrint = [&](int start, int end) {
          os_ << "\t";
          for (int k = start; k < end; k++) {
            int id = output[k];
            os_ << (delimited_ ? " " : "");
            if (!dict_.empty()) {
              CHECK_LT((size_t)id, dict_.size());
              os_ << dict_[id];
            } else {
              os_ << id;
            }
          }
        };

        if (arguments[j].hasSubseq()) {
          // print sequence with sub-sequence
          const int* subStarts =
              arguments[j].subSequenceStartPositions->getData(false);
          int subSeqId_start = 0;
          int subSeqId_end = 0;
          for (size_t k = 0; k < (size_t)arguments[j].getNumSubSequences() + 1;
               ++k) {
            if (starts[i] == subStarts[k]) subSeqId_start = k;
            if (starts[i + 1] == subStarts[k]) subSeqId_end = k;
          }
          for (int k = subSeqId_start; k < subSeqId_end; k++) {
            seqPrint(subStarts[k], subStarts[k + 1]);
            os_ << std::endl;
          }

        } else {
          // print sequence without sub-sequence
          if (arguments[j].in) {  // beam print
            real* probs = cpuIn_[j]->rowBuf(i);
            os_ << std::endl;
            int start = starts[i];
            int seqEnd = starts[i + 1];
            for (size_t k = 0; k < arguments[j].in->getWidth(); ++k) {
              if (start == seqEnd) {
                break;
              }
              int end = start + output[start] + 2;
              CHECK_LE(end, seqEnd);
              CHECK_EQ(output[end - 1], -1);
              os_ << k << "\t" << probs[k];
              seqPrint(start + 1, end - 1);
              os_ << std::endl;
              start = end;
            }
          } else {
            seqPrint(starts[i], starts[i + 1]);
          }
        }
      }
      os_ << std::endl;
    }
    return 0;
  }
};
REGISTER_EVALUATOR(seq_text_printer, SequenceTextPrinter);
Q
qijun 已提交
1314 1315 1316 1317 1318
/**
 * @brief print classification error.
 *
 * The config file api is classification_error_printer_evaluator.
 */
Z
zhangjinchao01 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
class ClassificationErrorPrinter : public ClassificationErrorEvaluator {
public:
  virtual void updateSamplesNum(const std::vector<Argument>& arguments) {}

  virtual real evalImp(std::vector<Argument>& arguments) {
    MatrixPtr errorMat = calcError(arguments);

    std::ostringstream os;
    errorMat->print(os);
    LOG(INFO) << "Printer=" << config_.name() << " Classification Error:\n"
              << os.str();

    if (auto startPos = arguments[0].sequenceStartPositions) {
      std::ostringstream os;
      startPos->getVector(false)->print(os, startPos->getSize());
      LOG(INFO) << "Printer=" << config_.name() << " sequence pos vector:\n"
                << os.str();
    }
    return 0;
  }
};
REGISTER_EVALUATOR(classification_error_printer, ClassificationErrorPrinter);

Y
Stash  
Yu Yang 已提交
1342 1343
std::string DummyEvaluator::getTypeImpl() const { return "dummy"; }

Z
zhangjinchao01 已提交
1344
}  // namespace paddle