This commit is contained in:
张壹 2024-10-25 10:27:08 +08:00
parent ec60030b91
commit f30834f7e6
2 changed files with 78 additions and 8 deletions

View File

@ -121,10 +121,13 @@ double gctl::loss_func::evaluate(const array<double> &x, array<double> &g)
double gctl::loss_func::evaluate(double inp, int id)
{
if (!init_) throw std::runtime_error("[gctl::loss_func] Not initialized.");
double val = (inp - tars_[id])/us_[id];
if (ntype_ == L1) val = fabs(val);
if (ntype_ == L2) val = val*val;
if (ntype_ == Lp) val = pow(val*val + eps_*eps_, 0.5*p_);
loss_ += val;
@ -133,6 +136,8 @@ double gctl::loss_func::evaluate(double inp, int id)
double gctl::loss_func::get_loss()
{
if (!init_) throw std::runtime_error("[gctl::loss_func] Not initialized.");
double l = loss_;
loss_ = 0.0;
@ -141,10 +146,13 @@ double gctl::loss_func::get_loss()
double gctl::loss_func::gradient(double inp, int id)
{
double val;
if (ntype_ == L1 && val >= 0) val = 1.0/(us_[id]*tnum_);
if (ntype_ == L1 && val < 0) val = -1.0/(us_[id]*tnum_);
if (ntype_ == L2) val = 2.0*(inp - tars_[id])/(us_[id]*us_[id]*tnum_);
if (!init_) throw std::runtime_error("[gctl::loss_func] Not initialized.");
double val = (inp - tars_[id])/us_[id];
if (ntype_ == L1 && val >= 0) val = 1.0/tnum_;
if (ntype_ == L1 && val < 0) val = -1.0/tnum_;
if (ntype_ == L2) val = 2.0*val/(us_[id]*tnum_);
if (ntype_ == Lp) val = p_*pow(val*val + eps_*eps_, 0.5*p_ - 1)*val/(us_[id]*tnum_);
return val;
}

View File

@ -33,21 +33,83 @@
namespace gctl
{
/**
* @brief L1范数, L2范数平方Lp范数定义的数据拟合差及相应的模型偏导数
* Phi = Lp(d - d^tar)^2/num(d)
*/
class loss_func
{
public:
loss_func();
loss_func(const array<double> &tar, norm_type_e n_type, double p = 2.0, double eps = 1e-16);
virtual ~loss_func();
loss_func(); ///< 构造函数
/**
* @brief
*
* @param tar
* @param n_type
* @param p Lp范数的阶次
* @param eps Lp范数分母内的小值
*/
loss_func(const array<double> &tar, norm_type_e n_type, double p = 2.0, double eps = 1e-16);
virtual ~loss_func(); ///< 析构函数
/**
* @brief
*
* @param tar
* @param n_type
* @param p Lp范数的阶次
* @param eps Lp范数分母内的小值
*/
void init(const array<double> &tar, norm_type_e n_type, double p = 2.0, double eps = 1e-16);
/**
* @brief
*
* @param uncer
*/
void set_uncertainty(double uncer);
/**
* @brief
*
* @param uncer
*/
void set_uncertainty(const array<double> &uncer);
/**
* @brief
*
* @param inp
* @param id
* @return
*/
double evaluate(double inp, int id);
/**
* @brief
*
* @param x
* @param g
* @return
*/
double evaluate(const array<double> &x, array<double> &g);
/**
* @brief 0
*
* @return
*/
double get_loss();
/**
* @brief
*
* @param inp
* @param id
* @return
*/
double gradient(double inp, int id);
private: