File: MultiCriterion.cc

package info (click to toggle)
torch 2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 5,488 kB
  • ctags: 3,217
  • sloc: cpp: 14,272; makefile: 201
file content (94 lines) | stat: -rw-r--r-- 2,373 bytes parent folder | download
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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (C) 2002 Samy Bengio (bengio@idiap.ch)
//                
//
// This file is part of Torch. Release II.
// [The Ultimate Machine Learning Library]
//
// Torch is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Torch is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Torch; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "MultiCriterion.h"

namespace Torch {

MultiCriterion::MultiCriterion(int n_criterions_,Criterion** criterions_,real* weights_)
{
  n_criterions = n_criterions_;
  criterions = criterions_;
  n_inputs = criterions[0]->n_inputs;
  weights = weights_;
  if (weights) {
    allocate_weights = false;
  } else {
    allocate_weights = true;
    weights = (real*)xalloc(sizeof(real)*n_criterions);
    for (int i=0;i<n_criterions;i++)
      weights[i] = 1.;
  }
}

void MultiCriterion::setDataSet(DataSet *data_)
{
  data = data_;
  for (int i=0;i<n_criterions;i++)
    criterions[i]->setDataSet(data_);
}

void MultiCriterion::iterInitialize()
{
  for (int i=0;i<n_criterions;i++)
    criterions[i]->iterInitialize();
}

void MultiCriterion::reset()
{
  for (int i=0;i<n_criterions;i++)
    criterions[i]->reset();
}

void MultiCriterion::forward(List *inputs)
{
  real *ptr_out = (real *)outputs->ptr;
  *ptr_out = 0.;
  real *w = weights;
  for (int i=0;i<n_criterions;i++) {
    criterions[i]->forward(inputs);
    *ptr_out += *((real*)criterions[i]->outputs->ptr) * *w++;
  }
}

void MultiCriterion::backward(List *inputs, real *alpha)
{
  real *b = beta;
  for (int i=0;i<n_inputs;i++)
    *b++ = 0;

  real *w = weights;
  for (int i=0;i<n_criterions;i++,w++) {
    criterions[i]->backward(inputs,alpha);
    b = beta;
    real* bi = criterions[i]->beta;
    for (int j=0;j<n_inputs;j++)
      *b++ += *bi++ * *w;
  }
}

MultiCriterion::~MultiCriterion()
{
  if (allocate_weights)
    free(weights);
}

}