SparseVector< Real > Class Template Reference

#include <sparse-matrix.h>

Collaboration diagram for SparseVector< Real >:

Public Member Functions

MatrixIndexT Dim () const
 
Real Sum () const
 
template<class OtherReal >
void CopyElementsToVec (VectorBase< OtherReal > *vec) const
 
template<class OtherReal >
void AddToVec (Real alpha, VectorBase< OtherReal > *vec) const
 
template<class OtherReal >
void CopyFromSvec (const SparseVector< OtherReal > &other)
 
SparseVector< Real > & operator= (const SparseVector< Real > &other)
 
 SparseVector (const SparseVector< Real > &other)
 
void Swap (SparseVector< Real > *other)
 
Real Max (int32 *index) const
 
MatrixIndexT NumElements () const
 Returns the number of nonzero elements. More...
 
const std::pair< MatrixIndexT, Real > & GetElement (MatrixIndexT i) const
 get an indexed element (0 <= i < NumElements()). More...
 
std::pair< MatrixIndexT, Real > * Data ()
 
const std::pair< MatrixIndexT, Real > * Data () const
 
void SetRandn (BaseFloat zero_prob)
 Sets elements to zero with probability zero_prob, else normally distributed. More...
 
 SparseVector ()
 
 SparseVector (MatrixIndexT dim)
 
 SparseVector (MatrixIndexT dim, const std::vector< std::pair< MatrixIndexT, Real > > &pairs)
 
 SparseVector (const VectorBase< Real > &vec)
 
void Resize (MatrixIndexT dim, MatrixResizeType resize_type=kSetZero)
 Resizes to this dimension. More...
 
void Write (std::ostream &os, bool binary) const
 
void Read (std::istream &os, bool binary)
 
void Scale (Real alpha)
 Scale all elements of sparse vector. More...
 

Private Attributes

MatrixIndexT dim_
 
std::vector< std::pair< MatrixIndexT, Real > > pairs_
 

Detailed Description

template<typename Real>
class kaldi::SparseVector< Real >

Definition at line 41 of file sparse-matrix.h.

Constructor & Destructor Documentation

◆ SparseVector() [1/5]

SparseVector ( const SparseVector< Real > &  other)
inline

Definition at line 60 of file sparse-matrix.h.

References SparseVector< Real >::Max(), and SparseVector< Real >::Swap().

60 { *this = other; }

◆ SparseVector() [2/5]

SparseVector ( )
inline

Definition at line 92 of file sparse-matrix.h.

Referenced by SparseVector< Real >::SparseVector().

92 : dim_(0) { }

◆ SparseVector() [3/5]

◆ SparseVector() [4/5]

SparseVector ( MatrixIndexT  dim,
const std::vector< std::pair< MatrixIndexT, Real > > &  pairs 
)

Definition at line 237 of file sparse-matrix.cc.

References SparseVector< Real >::dim_, KALDI_ASSERT, and SparseVector< Real >::pairs_.

238  :
239  dim_(dim),
240  pairs_(pairs) {
241  std::sort(pairs_.begin(), pairs_.end(),
242  sparse_vector_utils::CompareFirst<Real>());
243  typename std::vector<std::pair<MatrixIndexT, Real> >::iterator
244  out = pairs_.begin(), in = out, end = pairs_.end();
245  // special case: while there is nothing to be changed, skip over
246  // initial input (avoids unnecessary copying).
247  while (in + 1 < end && in[0].first != in[1].first && in[0].second != 0.0) {
248  in++;
249  out++;
250  }
251  while (in < end) {
252  // We reach this point only at the first element of
253  // each stretch of identical .first elements.
254  *out = *in;
255  ++in;
256  while (in < end && in->first == out->first) {
257  out->second += in->second; // this is the merge operation.
258  ++in;
259  }
260  if (out->second != Real(0.0)) // Don't keep zero elements.
261  out++;
262  }
263  pairs_.erase(out, end);
264  if (!pairs_.empty()) {
265  // range check.
266  KALDI_ASSERT(pairs_.front().first >= 0 && pairs_.back().first < dim_);
267  }
268 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SparseVector() [5/5]

SparseVector ( const VectorBase< Real > &  vec)
explicit

Definition at line 1213 of file sparse-matrix.cc.

References VectorBase< Real >::Data(), VectorBase< Real >::Dim(), and rnnlm::i.

1213  {
1214  MatrixIndexT dim = vec.Dim();
1215  dim_ = dim;
1216  if (dim == 0)
1217  return;
1218  const Real *ptr = vec.Data();
1219  for (MatrixIndexT i = 0; i < dim; i++) {
1220  Real val = ptr[i];
1221  if (val != 0.0)
1222  pairs_.push_back(std::pair<MatrixIndexT,Real>(i,val));
1223  }
1224 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
int32 MatrixIndexT
Definition: matrix-common.h:98

Member Function Documentation

◆ AddToVec()

template void AddToVec ( Real  alpha,
VectorBase< OtherReal > *  vec 
) const

Definition at line 84 of file sparse-matrix.cc.

References VectorBase< Real >::Data(), VectorBase< Real >::Dim(), and KALDI_ASSERT.

Referenced by SparseVector< Real >::Dim(), and kaldi::UnitTestSparseVectorAddToVec().

85  {
86  KALDI_ASSERT(vec->Dim() == dim_);
87  OtherReal *other_data = vec->Data();
88  typename std::vector<std::pair<MatrixIndexT, Real> >::const_iterator
89  iter = pairs_.begin(), end = pairs_.end();
90  if (alpha == 1.0) { // treat alpha==1.0 case specially.
91  for (; iter != end; ++iter)
92  other_data[iter->first] += iter->second;
93  } else {
94  for (; iter != end; ++iter)
95  other_data[iter->first] += alpha * iter->second;
96  }
97 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyElementsToVec()

template void CopyElementsToVec ( VectorBase< OtherReal > *  vec) const

Definition at line 64 of file sparse-matrix.cc.

References VectorBase< Real >::Data(), VectorBase< Real >::Dim(), KALDI_ASSERT, and VectorBase< Real >::SetZero().

Referenced by SparseVector< Real >::Dim(), kaldi::UnitTestSparseVectorAddToVec(), kaldi::UnitTestSparseVectorMax(), kaldi::UnitTestSparseVectorSum(), and kaldi::UnitTestSparseVectorVecSvec().

64  {
65  KALDI_ASSERT(vec->Dim() == this->dim_);
66  vec->SetZero();
67  OtherReal *other_data = vec->Data();
68  typename std::vector<std::pair<MatrixIndexT, Real> >::const_iterator
69  iter = pairs_.begin(), end = pairs_.end();
70  for (; iter != end; ++iter)
71  other_data[iter->first] = iter->second;
72 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyFromSvec()

template void CopyFromSvec ( const SparseVector< OtherReal > &  other)

Definition at line 111 of file sparse-matrix.cc.

References SparseVector< Real >::Dim(), SparseVector< Real >::GetElement(), rnnlm::i, and SparseVector< Real >::NumElements().

Referenced by SparseVector< Real >::Dim().

111  {
112  dim_ = other.Dim();
113  pairs_.clear();
114  if (dim_ == 0) return;
115  for (int32 i = 0; i < other.NumElements(); ++i) {
116  pairs_.push_back(std::make_pair(
117  other.GetElement(i).first,
118  static_cast<Real>(other.GetElement(i).second)));
119  }
120 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
kaldi::int32 int32

◆ Data() [1/2]

std::pair< MatrixIndexT, Real > * Data ( )

Definition at line 32 of file sparse-matrix.cc.

Referenced by NnetLdaStatsAccumulator::AccStatsFromOutput(), SparseMatrix< float >::AddToMat(), SparseMatrix< float >::CopyToMat(), SparseVector< Real >::GetElement(), SparseMatrix< float >::SparseMatrix(), kaldi::TraceMatSmat(), and kaldi::VecSvec().

32  {
33  if (pairs_.empty())
34  return NULL;
35  else
36  return &(pairs_[0]);
37 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_

◆ Data() [2/2]

const std::pair< MatrixIndexT, Real > * Data ( ) const

Definition at line 40 of file sparse-matrix.cc.

40  {
41  if (pairs_.empty())
42  return NULL;
43  else
44  return &(pairs_[0]);
45 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_

◆ Dim()

◆ GetElement()

const std::pair<MatrixIndexT, Real>& GetElement ( MatrixIndexT  i) const
inline

get an indexed element (0 <= i < NumElements()).

Definition at line 77 of file sparse-matrix.h.

References SparseVector< Real >::Data(), rnnlm::i, SparseVector< Real >::pairs_, and SparseVector< Real >::SetRandn().

Referenced by MatrixBase< float >::AddMatSmat(), MatrixBase< float >::AddSmat(), MatrixBase< float >::AddSmatMat(), and SparseVector< Real >::CopyFromSvec().

77  {
78  return pairs_[i];
79  }
std::vector< std::pair< MatrixIndexT, Real > > pairs_

◆ Max()

Real Max ( int32 index) const

Definition at line 1167 of file sparse-matrix.cc.

References KALDI_ASSERT.

Referenced by kaldi::nnet3::ComputeAccuracy(), SparseVector< Real >::SparseVector(), and kaldi::UnitTestSparseVectorMax().

1167  {
1168  KALDI_ASSERT(dim_ > 0 && pairs_.size() <= static_cast<size_t>(dim_));
1169  Real ans = -std::numeric_limits<Real>::infinity();
1170  int32 index = 0;
1171  typename std::vector<std::pair<MatrixIndexT, Real> >::const_iterator
1172  iter = pairs_.begin(), end = pairs_.end();
1173  for (; iter != end; ++iter) {
1174  if (iter->second > ans) {
1175  ans = iter->second;
1176  index = iter->first;
1177  }
1178  }
1179  if (ans >= 0 || pairs_.size() == dim_) {
1180  // ans >= 0 will be the normal case.
1181  // if pairs_.size() == dim_ then we need to return
1182  // even a negative answer as there are no spaces (hence no unlisted zeros).
1183  *index_out = index;
1184  return ans;
1185  }
1186  // all the stored elements are < 0, but there are unlisted
1187  // elements -> pick the first unlisted element.
1188  // Note that this class requires that the indexes are sorted
1189  // and unique.
1190  index = 0; // "index" will always be the next index, that
1191  // we haven't seen listed yet.
1192  iter = pairs_.begin();
1193  for (; iter != end; ++iter) {
1194  if (iter->first > index) { // index "index" is not listed.
1195  *index_out = index;
1196  return 0.0;
1197  } else {
1198  // index is the next potential gap in the indexes.
1199  index = iter->first + 1;
1200  }
1201  }
1202  // we can reach here if either pairs_.empty(), or
1203  // pairs_ is nonempty but contains a sequence (0, 1, 2,...).
1204  if (!pairs_.empty())
1205  index = pairs_.back().first + 1;
1206  // else leave index at zero
1207  KALDI_ASSERT(index < dim_);
1208  *index_out = index;
1209  return 0.0;
1210 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ NumElements()

◆ operator=()

SparseVector< Real > & operator= ( const SparseVector< Real > &  other)

Definition at line 132 of file sparse-matrix.cc.

References SparseVector< Real >::dim_, and SparseVector< Real >::pairs_.

Referenced by SparseVector< Real >::Dim(), and GeneralMatrix::GeneralMatrix().

133  {
134  this->CopyFromSvec(other);
135  dim_ = other.dim_;
136  pairs_ = other.pairs_;
137  return *this;
138 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
void CopyFromSvec(const SparseVector< OtherReal > &other)

◆ Read()

void Read ( std::istream &  os,
bool  binary 
)

Definition at line 173 of file sparse-matrix.cc.

References kaldi::ExpectToken(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, and kaldi::ReadBasicType().

Referenced by SparseMatrix< float >::Read(), SparseMatrix< float >::SparseMatrix(), and SparseVector< Real >::SparseVector().

173  {
174  if (binary) {
175  ExpectToken(is, binary, "SV");
176  ReadBasicType(is, binary, &dim_);
177  KALDI_ASSERT(dim_ >= 0);
178  int32 num_elems;
179  ReadBasicType(is, binary, &num_elems);
180  KALDI_ASSERT(num_elems >= 0 && num_elems <= dim_);
181  pairs_.resize(num_elems);
182  typename std::vector<std::pair<MatrixIndexT, Real> >::iterator
183  iter = pairs_.begin(), end = pairs_.end();
184  for (; iter != end; ++iter) {
185  ReadBasicType(is, binary, &(iter->first));
186  ReadBasicType(is, binary, &(iter->second));
187  }
188  } else {
189  // In text-mode, format is "dim=5 [ 0 0.2 3 0.9 ]
190  std::string str;
191  is >> str;
192  if (str.substr(0, 4) != "dim=")
193  KALDI_ERR << "Reading sparse vector, expected 'dim=xxx', got " << str;
194  std::string dim_str = str.substr(4, std::string::npos);
195  std::istringstream dim_istr(dim_str);
196  int32 dim = -1;
197  dim_istr >> dim;
198  if (dim < 0 || dim_istr.fail()) {
199  KALDI_ERR << "Reading sparse vector, expected 'dim=[int]', got " << str;
200  }
201  dim_ = dim;
202  is >> std::ws;
203  is >> str;
204  if (str != "[")
205  KALDI_ERR << "Reading sparse vector, expected '[', got " << str;
206  pairs_.clear();
207  while (1) {
208  is >> std::ws;
209  if (is.peek() == ']') {
210  is.get();
211  break;
212  }
213  MatrixIndexT i;
214  BaseFloat p;
215  is >> i >> p;
216  if (is.fail())
217  KALDI_ERR << "Error reading sparse vector, expecting numbers.";
218  KALDI_ASSERT(i >= 0 && i < dim
219  && (pairs_.empty() || i > pairs_.back().first));
220  pairs_.push_back(std::pair<MatrixIndexT, BaseFloat>(i, p));
221  }
222  }
223 }
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
std::vector< std::pair< MatrixIndexT, Real > > pairs_
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Resize()

void Resize ( MatrixIndexT  dim,
MatrixResizeType  resize_type = kSetZero 
)

Resizes to this dimension.

resize_type == kUndefined behaves the same as kSetZero.

Definition at line 280 of file sparse-matrix.cc.

References SparseVector< Real >::dim_, KALDI_ASSERT, kaldi::kCopyData, and SparseVector< Real >::pairs_.

Referenced by SparseMatrix< float >::SelectRows(), SparseMatrix< float >::SparseMatrix(), and SparseVector< Real >::SparseVector().

281  {
282  if (resize_type != kCopyData || dim == 0)
283  pairs_.clear();
284  KALDI_ASSERT(dim >= 0);
285  if (dim < dim_ && resize_type == kCopyData)
286  while (!pairs_.empty() && pairs_.back().first >= dim)
287  pairs_.pop_back();
288  dim_ = dim;
289 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Scale()

void Scale ( Real  alpha)

Scale all elements of sparse vector.

Definition at line 57 of file sparse-matrix.cc.

References rnnlm::i.

Referenced by SparseMatrix< float >::SparseMatrix(), and SparseVector< Real >::SparseVector().

57  {
58  for (int32 i = 0; i < pairs_.size(); ++i)
59  pairs_[i].second *= alpha;
60 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
kaldi::int32 int32

◆ SetRandn()

void SetRandn ( BaseFloat  zero_prob)

Sets elements to zero with probability zero_prob, else normally distributed.

Useful in testing.

Definition at line 271 of file sparse-matrix.cc.

References SparseVector< Real >::dim_, rnnlm::i, KALDI_ASSERT, SparseVector< Real >::pairs_, kaldi::RandGauss(), and kaldi::WithProb().

Referenced by SparseVector< Real >::GetElement(), SparseMatrix< float >::SparseMatrix(), kaldi::UnitTestSparseVectorAddToVec(), kaldi::UnitTestSparseVectorMax(), kaldi::UnitTestSparseVectorSum(), and kaldi::UnitTestSparseVectorVecSvec().

271  {
272  pairs_.clear();
273  KALDI_ASSERT(zero_prob >= 0 && zero_prob <= 1.0);
274  for (MatrixIndexT i = 0; i < dim_; i++)
275  if (WithProb(1.0 - zero_prob))
276  pairs_.push_back(std::pair<MatrixIndexT, Real>(i, RandGauss()));
277 }
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
std::vector< std::pair< MatrixIndexT, Real > > pairs_
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Sum()

Real Sum ( ) const

Definition at line 48 of file sparse-matrix.cc.

References rnnlm::i.

Referenced by kaldi::nnet3::ComputeAccuracy(), SparseVector< Real >::Dim(), and kaldi::UnitTestSparseVectorSum().

48  {
49  Real sum = 0;
50  for (int32 i = 0; i < pairs_.size(); ++i) {
51  sum += pairs_[i].second;
52  }
53  return sum;
54 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
kaldi::int32 int32

◆ Swap()

void Swap ( SparseVector< Real > *  other)

Definition at line 141 of file sparse-matrix.cc.

References SparseVector< Real >::dim_, SparseVector< Real >::pairs_, and kaldi::swap().

Referenced by SparseMatrix< float >::CopyFromSmat(), GeneralMatrix::GeneralMatrix(), SparseMatrix< float >::SparseMatrix(), and SparseVector< Real >::SparseVector().

141  {
142  pairs_.swap(other->pairs_);
143  std::swap(dim_, other->dim_);
144 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)

◆ Write()

void Write ( std::ostream &  os,
bool  binary 
) const

Definition at line 147 of file sparse-matrix.cc.

References kaldi::WriteBasicType(), and kaldi::WriteToken().

Referenced by SparseMatrix< float >::SparseMatrix(), SparseVector< Real >::SparseVector(), and SparseMatrix< float >::Write().

147  {
148  if (binary) {
149  WriteToken(os, binary, "SV");
150  WriteBasicType(os, binary, dim_);
151  MatrixIndexT num_elems = pairs_.size();
152  WriteBasicType(os, binary, num_elems);
153  typename std::vector<std::pair<MatrixIndexT, Real> >::const_iterator
154  iter = pairs_.begin(), end = pairs_.end();
155  for (; iter != end; ++iter) {
156  WriteBasicType(os, binary, iter->first);
157  WriteBasicType(os, binary, iter->second);
158  }
159  } else {
160  // In text-mode, use a human-friendly, script-friendly format;
161  // format is "dim=5 [ 0 0.2 3 0.9 ] "
162  os << "dim=" << dim_ << " [ ";
163  typename std::vector<std::pair<MatrixIndexT, Real> >::const_iterator
164  iter = pairs_.begin(), end = pairs_.end();
165  for (; iter != end; ++iter)
166  os << iter->first << ' ' << iter->second << ' ';
167  os << "] ";
168  }
169 }
std::vector< std::pair< MatrixIndexT, Real > > pairs_
int32 MatrixIndexT
Definition: matrix-common.h:98
void WriteToken(std::ostream &os, bool binary, const char *token)
The WriteToken functions are for writing nonempty sequences of non-space characters.
Definition: io-funcs.cc:134
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34

Member Data Documentation

◆ dim_

◆ pairs_


The documentation for this class was generated from the following files: