Skip to content

Commit

Permalink
numerically safe softmax in VW
Browse files Browse the repository at this point in the history
  • Loading branch information
ales-t committed Mar 10, 2016
1 parent 3e5c0e8 commit 7b52700
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions vw/Normalizer.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define moses_Normalizer_h

#include <vector>
#include <algorithm>
#include "Util.h"

namespace Discriminative
Expand Down Expand Up @@ -45,16 +46,25 @@ class SquaredLossNormalizer : public Normalizer
virtual ~SquaredLossNormalizer() {}
};

// safe softmax
class LogisticLossNormalizer : public Normalizer
{
public:
virtual void operator()(std::vector<float> &losses) const {
float sum = 0;
std::vector<float>::iterator it;

float sum = 0;
float max = 0;
for (it = losses.begin(); it != losses.end(); it++) {
*it = exp(-*it);
*it = -*it;
max = std::max(max, *it);
}

for (it = losses.begin(); it != losses.end(); it++) {
*it = exp(*it - max);
sum += *it;
}

for (it = losses.begin(); it != losses.end(); it++) {
*it /= sum;
}
Expand Down

0 comments on commit 7b52700

Please sign in to comment.