|
#ifndef moses_Normalizer_h |
|
#define moses_Normalizer_h |
|
|
|
#include <vector> |
|
#include <algorithm> |
|
#include "Util.h" |
|
|
|
namespace Discriminative |
|
{ |
|
|
|
class Normalizer |
|
{ |
|
public: |
|
virtual void operator()(std::vector<float> &losses) const = 0; |
|
virtual ~Normalizer() {} |
|
}; |
|
|
|
class SquaredLossNormalizer : public Normalizer |
|
{ |
|
public: |
|
virtual void operator()(std::vector<float> &losses) const { |
|
|
|
|
|
float sum = 0; |
|
|
|
|
|
std::vector<float>::iterator it; |
|
for (it = losses.begin(); it != losses.end(); it++) { |
|
if (*it <= 0.0) *it = 1.0; |
|
else if (*it >= 1.0) *it = 0.0; |
|
else *it = 1.0 - *it; |
|
sum += *it; |
|
} |
|
|
|
if (! Moses::Equals(sum, 0)) { |
|
|
|
for (it = losses.begin(); it != losses.end(); it++) |
|
*it /= sum; |
|
} else { |
|
|
|
for (it = losses.begin(); it != losses.end(); it++) |
|
*it = 1.0 / losses.size(); |
|
} |
|
} |
|
|
|
virtual ~SquaredLossNormalizer() {} |
|
}; |
|
|
|
|
|
class LogisticLossNormalizer : public Normalizer |
|
{ |
|
public: |
|
virtual void operator()(std::vector<float> &losses) const { |
|
std::vector<float>::iterator it; |
|
|
|
float sum = 0; |
|
float max = 0; |
|
for (it = losses.begin(); it != losses.end(); 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; |
|
} |
|
} |
|
|
|
virtual ~LogisticLossNormalizer() {} |
|
}; |
|
|
|
} |
|
|
|
#endif |
|
|