gmm-global-acc-stats-twofeats.cc
Go to the documentation of this file.
1 // gmmbin/gmm-global-acc-stats-twofeats.cc
2 
3 // Copyright 2009-2011 Microsoft Corporation; Saarland University
4 // 2014 Johns Hopkins University (author: Daniel Povey)
5 
6 // See ../../COPYING for clarification regarding multiple authors
7 //
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 //
12 // http://www.apache.org/licenses/LICENSE-2.0
13 //
14 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
16 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
17 // MERCHANTABLITY OR NON-INFRINGEMENT.
18 // See the Apache 2 License for the specific language governing permissions and
19 // limitations under the License.
20 
21 
22 #include "base/kaldi-common.h"
23 #include "util/common-utils.h"
24 #include "gmm/model-common.h"
25 #include "gmm/full-gmm.h"
26 #include "gmm/diag-gmm.h"
27 #include "gmm/mle-full-gmm.h"
28 
29 
30 int main(int argc, char *argv[]) {
31  try {
32  using namespace kaldi;
33 
34  const char *usage =
35  "Accumulate stats for training a diagonal-covariance GMM, two-feature version\n"
36  "First features are used to get posteriors, second to accumulate stats\n"
37  "Usage: gmm-global-acc-stats-twofeats [options] <model-in> "
38  "<feature1-rspecifier> <feature2-rspecifier> <stats-out>\n"
39  "e.g.: gmm-global-acc-stats-twofeats 1.mdl scp:train.scp scp:train2.scp 1.acc\n";
40 
41  ParseOptions po(usage);
42  bool binary = true;
43  std::string update_flags_str = "mvw";
44  std::string gselect_rspecifier, weights_rspecifier;
45  po.Register("binary", &binary, "Write output in binary mode");
46  po.Register("update-flags", &update_flags_str, "Which GMM parameters will be "
47  "updated: subset of mvw.");
48  po.Register("gselect", &gselect_rspecifier, "rspecifier for gselect objects "
49  "to limit the #Gaussians accessed on each frame.");
50  po.Register("weights", &weights_rspecifier, "rspecifier for a vector of floats "
51  "for each utterance, that's a per-frame weight.");
52  po.Read(argc, argv);
53 
54  if (po.NumArgs() != 4) {
55  po.PrintUsage();
56  exit(1);
57  }
58 
59  std::string model_filename = po.GetArg(1),
60  feature1_rspecifier = po.GetArg(2),
61  feature2_rspecifier = po.GetArg(3),
62  accs_wxfilename = po.GetArg(4);
63 
64  DiagGmm gmm;
65  {
66  bool binary_read;
67  Input ki(model_filename, &binary_read);
68  gmm.Read(ki.Stream(), binary_read);
69  }
70 
71  int32 new_dim = 0;
72  AccumDiagGmm gmm_accs;
73  // will initialize once we know new_dim.
74  // gmm_accs.Resize(gmm, StringToGmmFlags(update_flags_str));
75 
76  double tot_like = 0.0, tot_weight = 0.0;
77 
78  SequentialBaseFloatMatrixReader feature1_reader(feature1_rspecifier);
79  RandomAccessBaseFloatMatrixReader feature2_reader(feature2_rspecifier);
80  RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier);
81  RandomAccessBaseFloatVectorReader weights_reader(weights_rspecifier);
82  int32 num_done = 0, num_err = 0;
83 
84  for (; !feature1_reader.Done(); feature1_reader.Next()) {
85  std::string key = feature1_reader.Key();
86  if (!feature2_reader.HasKey(key)) {
87  KALDI_WARN << "For utterance " << key << ", second features not present.";
88  num_err++;
89  continue;
90  }
91  const Matrix<BaseFloat> &mat1 = feature1_reader.Value();
92  const Matrix<BaseFloat> &mat2 = feature2_reader.Value(key);
93  int32 file_frames = mat1.NumRows();
94  KALDI_ASSERT(mat1.NumRows() == mat2.NumRows());
95  if (new_dim == 0) {
96  new_dim = mat2.NumCols();
97  gmm_accs.Resize(gmm.NumGauss(), new_dim,
98  StringToGmmFlags(update_flags_str));
99  }
100  BaseFloat file_like = 0.0,
101  file_weight = 0.0; // total of weights of frames (will each be 1 unless
102  // --weights option supplied.
103  Vector<BaseFloat> weights;
104  if (weights_rspecifier != "") { // We have per-frame weighting.
105  if (!weights_reader.HasKey(key)) {
106  KALDI_WARN << "No per-frame weights available for utterance " << key;
107  num_err++;
108  continue;
109  }
110  weights = weights_reader.Value(key);
111  if (weights.Dim() != file_frames) {
112  KALDI_WARN << "Weights for utterance " << key << " have wrong dim "
113  << weights.Dim() << " vs. " << file_frames;
114  num_err++;
115  continue;
116  }
117  }
118  if (gselect_rspecifier != "") {
119  if (!gselect_reader.HasKey(key)) {
120  KALDI_WARN << "No gselect information for utterance " << key;
121  num_err++;
122  continue;
123  }
124  const std::vector<std::vector<int32> > &gselect =
125  gselect_reader.Value(key);
126  if (gselect.size() != static_cast<size_t>(file_frames)) {
127  KALDI_WARN << "gselect information for utterance " << key
128  << " has wrong size " << gselect.size() << " vs. "
129  << file_frames;
130  num_err++;
131  continue;
132  }
133 
134  for (int32 i = 0; i < file_frames; i++) {
135  BaseFloat weight = (weights.Dim() != 0) ? weights(i) : 1.0;
136  if (weight == 0.0) continue;
137  file_weight += weight;
138  SubVector<BaseFloat> data1(mat1, i), data2(mat2, i);
139  const std::vector<int32> &this_gselect = gselect[i];
140  int32 gselect_size = this_gselect.size();
141  KALDI_ASSERT(gselect_size > 0);
142  Vector<BaseFloat> loglikes;
143  gmm.LogLikelihoodsPreselect(data1, this_gselect, &loglikes);
144  file_like += weight * loglikes.ApplySoftMax();
145  loglikes.Scale(weight);
146  for (int32 j = 0; j < loglikes.Dim(); j++)
147  gmm_accs.AccumulateForComponent(data2, this_gselect[j], loglikes(j));
148  }
149  } else { // no gselect..
150  Vector<BaseFloat> posteriors;
151  for (int32 i = 0; i < file_frames; i++) {
152  BaseFloat weight = (weights.Dim() != 0) ? weights(i) : 1.0;
153  if (weight == 0.0) continue;
154  file_weight += weight;
155  file_like += weight * gmm.ComponentPosteriors(mat1.Row(i), &posteriors);
156  posteriors.Scale(weight);
157  gmm_accs.AccumulateFromPosteriors(mat2.Row(i), posteriors);
158  }
159  }
160  KALDI_VLOG(2) << "File '" << key << "': Average likelihood = "
161  << (file_like/file_weight) << " over "
162  << file_weight <<" frames.";
163  tot_like += file_like;
164  tot_weight += file_weight;
165  num_done++;
166  }
167  KALDI_LOG << "Done " << num_done << " files; "
168  << num_err << " with errors.";
169  KALDI_LOG << "Overall likelihood per "
170  << "frame = " << (tot_like/tot_weight) << " over " << tot_weight
171  << " (weighted) frames.";
172 
173  WriteKaldiObject(gmm_accs, accs_wxfilename, binary);
174  KALDI_LOG << "Written accs to " << accs_wxfilename;
175  return (num_done != 0 ? 0 : 1);
176  } catch(const std::exception &e) {
177  std::cerr << e.what();
178  return -1;
179  }
180 }
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
void LogLikelihoodsPreselect(const VectorBase< BaseFloat > &data, const std::vector< int32 > &indices, Vector< BaseFloat > *loglikes) const
Outputs the per-component log-likelihoods of a subset of mixture components.
Definition: diag-gmm.cc:566
GmmFlagsType StringToGmmFlags(std::string str)
Convert string which is some subset of "mSwa" to flags.
Definition: model-common.cc:26
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
kaldi::int32 int32
Real ApplySoftMax()
Apply soft-max to vector and return normalizer (log sum of exponentials).
void Register(const std::string &name, bool *ptr, const std::string &doc)
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
std::istream & Stream()
Definition: kaldi-io.cc:826
BaseFloat ComponentPosteriors(const VectorBase< BaseFloat > &data, Vector< BaseFloat > *posteriors) const
Computes the posterior probabilities of all Gaussian components given a data point.
Definition: diag-gmm.cc:601
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
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
const T & Value(const std::string &key)
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
void AccumulateForComponent(const VectorBase< BaseFloat > &data, int32 comp_index, BaseFloat weight)
Accumulate for a single component, given the posterior.
int Read(int argc, const char *const *argv)
Parses the command line options and fills the ParseOptions-registered variables.
int main(int argc, char *argv[])
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
int32 NumGauss() const
Returns the number of mixture components in the GMM.
Definition: diag-gmm.h:72
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
void Scale(Real alpha)
Multiplies all elements by this constant.
bool HasKey(const std::string &key)
int NumArgs() const
Number of positional parameters (c.f. argc-1).
void Read(std::istream &in, bool binary)
Definition: diag-gmm.cc:728
A class representing a vector.
Definition: kaldi-vector.h:406
#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
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
Definition for Gaussian Mixture Model with diagonal covariances.
Definition: diag-gmm.h:42
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
void Resize(int32 num_gauss, int32 dim, GmmFlagsType flags)
Allocates memory for accumulators.
#define KALDI_LOG
Definition: kaldi-error.h:153
void AccumulateFromPosteriors(const VectorBase< BaseFloat > &data, const VectorBase< BaseFloat > &gauss_posteriors)
Accumulate for all components, given the posteriors.
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501