Skip to content
Snippets Groups Projects
NeuralNetwork.cpp 5.12 KiB
/*Copyright (c) 2019 Alexis Nasr && Franck Dary

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:i

 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

#include "NeuralNetwork.hpp"

int NeuralNetwork::randomSeed = 0;
bool NeuralNetwork::dynetIsInit = false;

NeuralNetwork::~NeuralNetwork() {};

std::string NeuralNetwork::expression2str(dynet::Expression & expr)
{
  std::string result = "";

  auto elem = dynet::as_vector(expr.value());

  for (auto & f : elem)
    result += util::float2str(f, "%f") + " ";

  if (!result.empty())
  result.pop_back();

  return result;
}

dynet::ParameterCollection & NeuralNetwork::getModel()
{
  return model;
}

dynet::Expression NeuralNetwork::featValue2Expression(dynet::ComputationGraph & cg, const FeatureModel::FeatureValue & fv)
{
  if (fv.dicts.empty())
  {
    fprintf(stderr, "ERROR (%s) : FeatureValue is empty, cannot get its expression. Aborting.\n", ERRINFO);
    exit(1);
  }

  std::vector<dynet::Expression> expressions;

  for (unsigned int i = 0; i < fv.dicts.size(); i++)
  {
    Dict * dict = fv.dicts[i];
    bool isConst = (fv.policies[i] == FeatureModel::Policy::Final) || (dict->mode == Dict::Mode::OneHot);

    auto & lu = dict->getLookupParameter();
    unsigned int index = dict->getValue(fv.values[i]);

    if(isConst)
      expressions.emplace_back(dynet::const_lookup(cg, lu, index));
    else
      expressions.emplace_back(dynet::lookup(cg, lu, index));
  }

  if (fv.func == FeatureModel::Function::Mean)
    return dynet::average(expressions);

  return dynet::concatenate(expressions);
}

dynet::DynetParams & NeuralNetwork::getDefaultParams()
{
  static dynet::DynetParams params;
  params.random_seed = randomSeed;
  std::srand(params.random_seed);

  return params;
}

void NeuralNetwork::initDynet()
{
  if(dynetIsInit)
    return;

  dynetIsInit = true;
  dynet::initialize(getDefaultParams());
}

std::string NeuralNetwork::activation2str(Activation a)
{
  switch(a)
  {
    case LINEAR :
      return "LINEAR";
      break;
    case RELU :
      return "RELU";
      break;
    case ELU :
      return "ELU";
      break;
    case CUBE :
      return "CUBE";
      break;
    case SIGMOID :
      return "SIGMOID";
      break;
    case TANH :
      return "TANH";
      break;
    case SOFTMAX :
      return "SOFTMAX";
      break;
    case SPARSEMAX :
      return "SPARSEMAX";
      break;
    default :
      break;
  }

  return "UNKNOWN";
}

NeuralNetwork::Activation NeuralNetwork::str2activation(std::string s)
{
  if(s == "LINEAR")
    return LINEAR;
  else if(s == "RELU")
    return RELU;
  else if(s == "ELU")
    return ELU;
  else if(s == "CUBE")
    return CUBE;
  else if(s == "SIGMOID")
    return SIGMOID;
  else if(s == "TANH")
    return TANH;
  else if(s == "SOFTMAX")
    return SOFTMAX;
  else if(s == "SPARSEMAX")
    return SPARSEMAX;
  else
  {
    fprintf(stderr, "ERROR (%s) : invalid activation \'%s\'. Aborting\n",ERRINFO, s.c_str());
    exit(1);
  }

  return LINEAR;
}

NeuralNetwork::Layer::Layer(int input_dim, int output_dim,
                            float dropout_rate, Activation activation)
{
  this->input_dim = input_dim;
  this->output_dim = output_dim;
  this->dropout_rate = dropout_rate;
  this->activation = activation;
}

dynet::Expression NeuralNetwork::activate(dynet::Expression h, Activation f)
{
  switch(f)
  {
    case LINEAR :
      return h;
      break;
    case RELU :
      return rectify(h);
      break;
    case ELU :
      return elu(h);
      break;
    case SIGMOID :
      return logistic(h);
      break;
    case TANH :
      return tanh(h);
      break;
    case SOFTMAX :
      return softmax(h);
      break;
    default :
      break;
  }

  fprintf(stderr, "ERROR (%s) : Activation not implemented \'%s\'. Aborting.\n", ERRINFO, activation2str(f).c_str());
  exit(1);

  return h;
}

unsigned int NeuralNetwork::featureSize(const FeatureModel::FeatureValue & fv)
{
  unsigned int res = 0;

  if (fv.func == FeatureModel::Function::Concat)
    for (auto dict : fv.dicts)
      res += dict->getDimension();
  else if (fv.func == FeatureModel::Function::Mean)
    res = fv.dicts[0]->getDimension();

  return res;
}

void NeuralNetwork::setBatchSize(int batchSize)
{
  this->batchSize = batchSize;
}

int NeuralNetwork::getBatchSize()
{
  return batchSize;
}