Loss.h 2.33 KB
Newer Older
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
/* NiuTrans.Tensor - an open-source tensor library
 * Copyright (C) 2017, Natural Language Processing Lab, Northestern University. 
 * All rights reserved.
 *
 * 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.
 */

/*
* $Created by: XIAO Tong (email: xiaotong@mail.neu.edu.cn) 2018-04-24
* Good start of the new project - but full of meetings today.
*/

#ifndef __LOSS_H__
#define __LOSS_H__

#include "../XTensor.h"

namespace nts{ // namespace nts(NiuTrans.Tensor)

/*
loss function name, e.g., crossentropy.
*/
enum LOSS_FUNCTION_NAME {
NOLOSS, 
SQUAREDERROR,  // loss = sum_{i} 0.5*(t_i - y_i)^2, where t_i is the gold standard and y_i is the model output
               // dloss/dy_i = y_i - t_i
               // it is actually a squared euclidean distance
CROSSENTROPY,  // loss = sum_{i} (-t_i * log(y_i)), where t and y are distributions 
               // dloss/dy_i = -t_i / y_i
ONEHOTERROR    // loss = sum_{i} e_i
               // where e_i = 0.5*(t_i - y_i)^2 if t_i = 1, 
               // e_i = 0 otherwise
};

/*
loss function to measure the "number" of errors
*/

/* compute the loss */
50
DTYPE _LossCompute(XTensor * gold, XTensor * output, LOSS_FUNCTION_NAME LFName,
51
                   bool isLogOutput, int leadDim, int gBeg, int gLen, int oBeg);
52 53

/* compute the loss (log version) */
54
DTYPE _LossComputeForLogScale(XTensor * gold, XTensor * output, LOSS_FUNCTION_NAME LFName,
55
                              int leadDim, int gBeg, int gLen, int oBeg);
56 57

/* backward compuation for a single element */
58
DTYPE _LossBackwardPoint(DTYPE t, DTYPE y, LOSS_FUNCTION_NAME LFName);
59 60

/* backward compuation for (dense) vectors */
61
void _LossBackward(XTensor * dEdY, XTensor * t, XTensor * y, 
62 63
                   LOSS_FUNCTION_NAME LFName, 
                   int leadDim = -1, int tBeg = 0, int tLen = -1, int yBeg = 0);
64 65 66

} // namespace nts(NiuTrans.Tensor)

67
#endif // __LOSS_H__