gmm-init-mono.cc
Go to the documentation of this file.
1 // gmmbin/gmm-init-mono.cc
2 
3 // Copyright 2009-2011 Microsoft Corporation
4 
5 // See ../../COPYING for clarification regarding multiple authors
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16 // MERCHANTABLITY OR NON-INFRINGEMENT.
17 // See the Apache 2 License for the specific language governing permissions and
18 // limitations under the License.
19 
20 
21 #include "base/kaldi-common.h"
22 #include "util/common-utils.h"
23 #include "gmm/am-diag-gmm.h"
24 #include "hmm/hmm-topology.h"
25 #include "hmm/transition-model.h"
26 #include "tree/context-dep.h"
27 
28 namespace kaldi {
29 // This function reads a file like:
30 // 1 2 3
31 // 4 5
32 // 6 7 8
33 // where each line is a list of integer id's of phones (that should have their pdfs shared).
34 void ReadSharedPhonesList(std::string rxfilename, std::vector<std::vector<int32> > *list_out) {
35  list_out->clear();
36  Input input(rxfilename);
37  std::istream &is = input.Stream();
38  std::string line;
39  while (std::getline(is, line)) {
40  list_out->push_back(std::vector<int32>());
41  if (!SplitStringToIntegers(line, " \t\r", true, &(list_out->back())))
42  KALDI_ERR << "Bad line in shared phones list: " << line << " (reading "
43  << PrintableRxfilename(rxfilename) << ")";
44  std::sort(list_out->rbegin()->begin(), list_out->rbegin()->end());
45  if (!IsSortedAndUniq(*(list_out->rbegin())))
46  KALDI_ERR << "Bad line in shared phones list (repeated phone): " << line
47  << " (reading " << PrintableRxfilename(rxfilename) << ")";
48  }
49 }
50 
51 } // end namespace kaldi
52 
53 int main(int argc, char *argv[]) {
54  try {
55  using namespace kaldi;
56  using kaldi::int32;
57 
58  const char *usage =
59  "Initialize monophone GMM.\n"
60  "Usage: gmm-init-mono <topology-in> <dim> <model-out> <tree-out> \n"
61  "e.g.: \n"
62  " gmm-init-mono topo 39 mono.mdl mono.tree\n";
63 
64  bool binary = true;
65  std::string train_feats;
66  std::string shared_phones_rxfilename;
67  BaseFloat perturb_factor = 0.0;
68  ParseOptions po(usage);
69  po.Register("binary", &binary, "Write output in binary mode");
70  po.Register("train-feats", &train_feats,
71  "rspecifier for training features [used to set mean and variance]");
72  po.Register("shared-phones", &shared_phones_rxfilename,
73  "rxfilename containing, on each line, a list of phones whose pdfs should be shared.");
74  po.Register("perturb-factor", &perturb_factor,
75  "Perturb the means using this fraction of standard deviation.");
76  po.Read(argc, argv);
77 
78  if (po.NumArgs() != 4) {
79  po.PrintUsage();
80  exit(1);
81  }
82 
83 
84  std::string topo_filename = po.GetArg(1);
85  int dim = atoi(po.GetArg(2).c_str());
86  KALDI_ASSERT(dim> 0 && dim < 10000);
87  std::string model_filename = po.GetArg(3);
88  std::string tree_filename = po.GetArg(4);
89 
90  Vector<BaseFloat> glob_inv_var(dim);
91  glob_inv_var.Set(1.0);
92  Vector<BaseFloat> glob_mean(dim);
93  glob_mean.Set(1.0);
94 
95  if (train_feats != "") {
96  double count = 0.0;
97  Vector<double> var_stats(dim);
98  Vector<double> mean_stats(dim);
99  SequentialDoubleMatrixReader feat_reader(train_feats);
100  for (; !feat_reader.Done(); feat_reader.Next()) {
101  const Matrix<double> &mat = feat_reader.Value();
102  for (int32 i = 0; i < mat.NumRows(); i++) {
103  count += 1.0;
104  var_stats.AddVec2(1.0, mat.Row(i));
105  mean_stats.AddVec(1.0, mat.Row(i));
106  }
107  }
108  if (count == 0) { KALDI_ERR << "no features were seen."; }
109  var_stats.Scale(1.0/count);
110  mean_stats.Scale(1.0/count);
111  var_stats.AddVec2(-1.0, mean_stats);
112  if (var_stats.Min() <= 0.0)
113  KALDI_ERR << "bad variance";
114  var_stats.InvertElements();
115  glob_inv_var.CopyFromVec(var_stats);
116  glob_mean.CopyFromVec(mean_stats);
117  }
118 
119  HmmTopology topo;
120  bool binary_in;
121  Input ki(topo_filename, &binary_in);
122  topo.Read(ki.Stream(), binary_in);
123 
124  const std::vector<int32> &phones = topo.GetPhones();
125 
126  std::vector<int32> phone2num_pdf_classes (1+phones.back());
127  for (size_t i = 0; i < phones.size(); i++)
128  phone2num_pdf_classes[phones[i]] = topo.NumPdfClasses(phones[i]);
129 
130  // Now the tree [not really a tree at this point]:
131  ContextDependency *ctx_dep = NULL;
132  if (shared_phones_rxfilename == "") { // No sharing of phones: standard approach.
133  ctx_dep = MonophoneContextDependency(phones, phone2num_pdf_classes);
134  } else {
135  std::vector<std::vector<int32> > shared_phones;
136  ReadSharedPhonesList(shared_phones_rxfilename, &shared_phones);
137  // ReadSharedPhonesList crashes on error.
138  ctx_dep = MonophoneContextDependencyShared(shared_phones, phone2num_pdf_classes);
139  }
140 
141  int32 num_pdfs = ctx_dep->NumPdfs();
142 
143  AmDiagGmm am_gmm;
144  DiagGmm gmm;
145  gmm.Resize(1, dim);
146  { // Initialize the gmm.
147  Matrix<BaseFloat> inv_var(1, dim);
148  inv_var.Row(0).CopyFromVec(glob_inv_var);
149  Matrix<BaseFloat> mu(1, dim);
150  mu.Row(0).CopyFromVec(glob_mean);
151  Vector<BaseFloat> weights(1);
152  weights.Set(1.0);
153  gmm.SetInvVarsAndMeans(inv_var, mu);
154  gmm.SetWeights(weights);
155  gmm.ComputeGconsts();
156  }
157 
158  for (int i = 0; i < num_pdfs; i++)
159  am_gmm.AddPdf(gmm);
160 
161  if (perturb_factor != 0.0) {
162  for (int i = 0; i < num_pdfs; i++)
163  am_gmm.GetPdf(i).Perturb(perturb_factor);
164  }
165 
166  // Now the transition model:
167  TransitionModel trans_model(*ctx_dep, topo);
168 
169  {
170  Output ko(model_filename, binary);
171  trans_model.Write(ko.Stream(), binary);
172  am_gmm.Write(ko.Stream(), binary);
173  }
174 
175  // Now write the tree.
176  ctx_dep->Write(Output(tree_filename, binary).Stream(),
177  binary);
178 
179  delete ctx_dep;
180  return 0;
181  } catch(const std::exception &e) {
182  std::cerr << e.what();
183  return -1;
184  }
185 }
186 
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
void AddPdf(const DiagGmm &gmm)
Adds a GMM to the model, and increments the total number of PDFs.
Definition: am-diag-gmm.cc:57
void Perturb(float perturb_factor)
Perturbs the component means with a random vector multiplied by the pertrub factor.
Definition: diag-gmm.cc:215
void SetInvVarsAndMeans(const MatrixBase< Real > &invvars, const MatrixBase< Real > &means)
Use SetInvVarsAndMeans if updating both means and (inverse) variances.
Definition: diag-gmm-inl.h:63
A class for storing topology information for phones.
Definition: hmm-topology.h:93
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
int main(int argc, char *argv[])
ContextDependency * MonophoneContextDependency(const std::vector< int32 > &phones, const std::vector< int32 > &phone2num_pdf_classes)
Definition: context-dep.cc:331
void Resize(int32 nMix, int32 dim)
Resizes arrays to this dim. Does not initialize data.
Definition: diag-gmm.cc:66
ContextDependency * MonophoneContextDependencyShared(const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes)
Definition: context-dep.cc:343
int32 ComputeGconsts()
Sets the gconsts.
Definition: diag-gmm.cc:114
kaldi::int32 int32
void Read(std::istream &is, bool binary)
Definition: hmm-topology.cc:39
Real Min() const
Returns the minimum value of any element, or +infinity for the empty vector.
void Register(const std::string &name, bool *ptr, const std::string &doc)
int32 NumPdfClasses(int32 phone) const
Returns the number of pdf-classes for this phone; throws exception if phone not covered by this topol...
void ReadSharedPhonesList(std::string rxfilename, std::vector< std::vector< int32 > > *list_out)
void AddVec2(const Real alpha, const VectorBase< Real > &v)
Add vector : *this = *this + alpha * rv^2 [element-wise squaring].
virtual int32 NumPdfs() const
NumPdfs() returns the number of acoustic pdfs (they are numbered 0.. NumPdfs()-1).
Definition: context-dep.h:71
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
void Write(std::ostream &os, bool binary) const
Definition: context-dep.cc:145
std::ostream & Stream()
Definition: kaldi-io.cc:701
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Read(int argc, const char *const *argv)
Parses the command line options and fills the ParseOptions-registered variables.
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
void Scale(Real alpha)
Multiplies all elements by this constant.
const std::vector< int32 > & GetPhones() const
Returns a reference to a sorted, unique list of phones covered by the topology (these phones will be ...
Definition: hmm-topology.h:163
int NumArgs() const
Number of positional parameters (c.f. argc-1).
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
void Write(std::ostream &os, bool binary) const
A class representing a vector.
Definition: kaldi-vector.h:406
void InvertElements()
Invert all elements.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Set(Real f)
Set all members of a vector to a specified value.
void Write(std::ostream &out_stream, bool binary) const
Definition: am-diag-gmm.cc:163
Definition for Gaussian Mixture Model with diagonal covariances.
Definition: diag-gmm.h:42
std::string PrintableRxfilename(const std::string &rxfilename)
PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:61
void SetWeights(const VectorBase< Real > &w)
Mutators for both float or double.
Definition: diag-gmm-inl.h:28
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...