rapidXMM.cpp 6.44 KB
Newer Older
Joseph Larralde's avatar
Joseph Larralde committed
1
#include "rapidXMM.h"
2
3
#include "../trainingData.h"
#include "../machineLearning.h"
Joseph Larralde's avatar
Joseph Larralde committed
4
5

static bool trainingData2xmmTrainingSet(const rapidmix::trainingData& data, xmm::TrainingSet& set) {
6
  if (data.trainingSet.size() < 1) {
Joseph Larralde's avatar
Joseph Larralde committed
7
8
9
    return false;
  }

10
  if (data.trainingSet.size() > 0 && data.trainingSet[0].elements.size() == 0) {
Joseph Larralde's avatar
Joseph Larralde committed
11
12
13
14
    // empty recorded phrase
    return false;
  }

15
  rapidmix::trainingData::element el = data.trainingSet[0].elements[0];
Joseph Larralde's avatar
Joseph Larralde committed
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
  int dimIn = static_cast<int>(el.input.size());
  int dimOut = static_cast<int>(el.output.size());

  // translate and return true if data and set are compatible
  // don't translate and return false otherwise

  if (dimOut > 0 != set.bimodal()) {
    return false;
  }

  xmm::Phrase xp;

  if (set.bimodal()) {
    set.dimension.set(dimIn + dimOut);
    set.dimension_input.set(dimIn);
    xp = xmm::Phrase(xmm::MemoryMode::OwnMemory, xmm::Multimodality::Bimodal);
    xp.dimension.set(dimIn + dimOut);
    xp.dimension_input.set(dimIn);
  } else {
    set.dimension.set(dimIn);
    set.dimension_input.set(0);
    xp = xmm::Phrase(xmm::MemoryMode::OwnMemory, xmm::Multimodality::Unimodal);
    xp.dimension.set(dimIn);
    xp.dimension_input.set(0);
  }

  set.clear();

  //for (auto &phrase : data.trainingSet) {
45
  for (int i = 0; i < data.trainingSet.size(); ++i) {
Joseph Larralde's avatar
Joseph Larralde committed
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
    const rapidmix::trainingData::phrase &phrase = data.trainingSet[i];
    xp.clear();
    xp.label.set(phrase.label);

    for (auto &element : phrase.elements) {
      std::vector<float> obsIn(element.input.begin(), element.input.end());
      std::vector<float> obsOut(element.output.begin(), element.output.end());
      std::vector<float> obs;
      obs.insert(obs.end(), obsIn.begin(), obsIn.end());
      obs.insert(obs.end(), obsOut.begin(), obsOut.end());
      xp.record(obs);
    }

    set.addPhrase(static_cast<int>(set.size()), xp);
  }

  return true;
}

//=============================== xmmTool ====================================//

template <class SingleClassModel, class Model>
bool xmmTool<SingleClassModel, Model>::train(const rapidmix::trainingData& newTrainingData) {
  if (trainingData2xmmTrainingSet(newTrainingData, set)) {
    model.train(&set);
    model.reset();
    return true;
  }

  return false;
}

////////// private JSON data manipulation methods :

//TODO: add a type field (gmm/gmr/hmm/hmr) in metadata when family is xmm
template <class SingleClassModel, class Model>
Json::Value xmmTool<SingleClassModel, Model>::toJSON(/*std::string modelType*/) {
  Json::Value root;

Joseph Larralde's avatar
Joseph Larralde committed
85
86
  root["docType"] = "rapid-mix:ml-model";
  root["docVersion"] = RAPIDMIX_JSON_DOC_VERSION;
Joseph Larralde's avatar
Joseph Larralde committed
87

Joseph Larralde's avatar
Joseph Larralde committed
88
89
90
91
92
93
94
  Json::Value target;

  target["name"] = "xmm";
  target["version"] = "v1.0.0";

  root["target"] = target;
  root["payload"] = model.toJson();
Joseph Larralde's avatar
Joseph Larralde committed
95
96
97
98
99
100

  return root;
}

template <class SingleClassModel, class Model>
bool xmmTool<SingleClassModel, Model>::fromJSON(Json::Value &jm) {
Joseph Larralde's avatar
Joseph Larralde committed
101
102
103
104
  if (jm["docType"].asString().compare("rapid-mix:ml-model") == 0 &&
      jm["target"]["name"].asString().compare("xmm") == 0 &&
      jm["payload"].size() > 0) {
    model.fromJson(jm["payload"]);
Joseph Larralde's avatar
Joseph Larralde committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    model.reset();
    return true;
  }

  return false;
}

////////// public JSON file manipulation interface :

template <class SingleClassModel, class Model>
std::string xmmTool<SingleClassModel, Model>::getJSON() {
  Json::Value result = toJSON();
  return result.toStyledString();
}

template <class SingleClassModel, class Model>
void xmmTool<SingleClassModel, Model>::writeJSON(const std::string &filepath) {
  Json::Value root = toJSON();
  std::ofstream jsonOut;
  jsonOut.open (filepath);
  Json::StyledStreamWriter writer;
  writer.write(jsonOut, root);
  jsonOut.close();
}

template <class SingleClassModel, class Model>
bool xmmTool<SingleClassModel, Model>::putJSON(const std::string &jsonMessage) {
  Json::Value parsedFromString;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse(jsonMessage, parsedFromString);
  return (parsingSuccessful && fromJSON(parsedFromString));
}

template <class SingleClassModel, class Model>
bool xmmTool<SingleClassModel, Model>::readJSON(const std::string &filepath) {
  Json::Value root;
  std::ifstream file(filepath);
  file >> root;
  return fromJSON(root);
}

//============================== xmmGmmTool ==================================//

148
std::vector<double> rapidXmmGmm::run(const std::vector<double>& inputVector) {
Joseph Larralde's avatar
Joseph Larralde committed
149
150
151
152
153
154
  xmmTool::preProcess(inputVector);
  return model.results.smoothed_normalized_likelihoods;
}

//============================== xmmGmrTool ==================================//

155
std::vector<double> rapidXmmGmr::run(const std::vector<double>& inputVector) {
Joseph Larralde's avatar
Joseph Larralde committed
156
157
158
159
160
161
162
163
  xmmTool::preProcess(inputVector);
  std::vector<float> *res = &model.results.output_values;
  std::vector<double> dRes(res->begin(), res->end());
  return dRes;
}

//============================== xmmHmmTool ==================================//

164
std::vector<double> rapidXmmHmm::run(const std::vector<double>& inputVector) {
Joseph Larralde's avatar
Joseph Larralde committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  xmmTool::preProcess(inputVector);
  std::vector<double> res;

  int i(0);
  for (auto &m : model.models) {
    res.push_back(model.results.smoothed_normalized_likelihoods[i]);
    res.push_back(m.second.results.progress);
    i++;
  }

  return res;
}

//============================== xmmHmrTool ==================================//

180
std::vector<double> rapidXmmHmr::run(const std::vector<double>& inputVector) {
Joseph Larralde's avatar
Joseph Larralde committed
181
182
183
184
185
186
187
  xmmTool::preProcess(inputVector);
  std::vector<float> *res = &model.results.output_values;
  std::vector<double> dRes(res->begin(), res->end());
  return dRes;
}

///////////////////////////////////////////////////////////////////////////
188
///// generic train method and forward declaration of specialized templates
Joseph Larralde's avatar
Joseph Larralde committed
189
190
///////////////////////////////////////////////////////////////////////////

191
192
193
194
195
196
template class xmmTool<xmm::GMM, xmm::GMM>;
template class xmmTool<xmm::HMM, xmm::HierarchicalHMM>;

template class xmmStaticTool<xmm::GMM, xmm::GMM>;
template class xmmTemporalTool<xmm::HMM, xmm::HierarchicalHMM>;

197
198
//I wonder why this can't be defined in machineLearning.cpp? -MZ

199
200
201
// It is needed by the template instantiations below.
// You get an undefined symbols error otherwise.

Joseph Larralde's avatar
Joseph Larralde committed
202
203
204
205
206
template <class MachineLearningModule>
bool rapidmix::machineLearning<MachineLearningModule>::train(const trainingData &newTrainingData) {
    return MachineLearningModule::train(newTrainingData);
}

207
208
209
210
template class rapidmix::machineLearning<rapidXmmGmm>;
template class rapidmix::machineLearning<rapidXmmGmr>;
template class rapidmix::machineLearning<rapidXmmHmm>;
template class rapidmix::machineLearning<rapidXmmHmr>;
Joseph Larralde's avatar
Joseph Larralde committed
211