VectorBase< Real > Class Template Reference

Provides a vector abstraction class. More...

#include <kaldi-vector.h>

Inheritance diagram for VectorBase< Real >:
Collaboration diagram for VectorBase< Real >:

Public Member Functions

void SetZero ()
 Set vector to all zeros. More...
 
bool IsZero (Real cutoff=1.0e-06) const
 Returns true if matrix is all zeros. More...
 
void Set (Real f)
 Set all members of a vector to a specified value. More...
 
void SetRandn ()
 Set vector to random normally-distributed noise. More...
 
void SetRandUniform ()
 Sets to numbers uniformly distributed on (0,1) More...
 
MatrixIndexT RandCategorical () const
 This function returns a random index into this vector, chosen with probability proportional to the corresponding element. More...
 
MatrixIndexT Dim () const
 Returns the dimension of the vector. More...
 
MatrixIndexT SizeInBytes () const
 Returns the size in memory of the vector, in bytes. More...
 
Real * Data ()
 Returns a pointer to the start of the vector's data. More...
 
const Real * Data () const
 Returns a pointer to the start of the vector's data (const). More...
 
Real operator() (MatrixIndexT i) const
 Indexing operator (const). More...
 
Real & operator() (MatrixIndexT i)
 Indexing operator (non-const). More...
 
SubVector< Real > Range (const MatrixIndexT o, const MatrixIndexT l)
 Returns a sub-vector of a vector (a range of elements). More...
 
const SubVector< Real > Range (const MatrixIndexT o, const MatrixIndexT l) const
 Returns a const sub-vector of a vector (a range of elements). More...
 
void CopyFromVec (const VectorBase< Real > &v)
 Copy data from another vector (must match own size). More...
 
template<typename OtherReal >
void CopyFromPacked (const PackedMatrix< OtherReal > &M)
 Copy data from a SpMatrix or TpMatrix (must match own size). More...
 
template<typename OtherReal >
void CopyFromVec (const VectorBase< OtherReal > &v)
 Copy data from another vector of different type (double vs. float) More...
 
template<typename OtherReal >
void CopyFromVec (const CuVectorBase< OtherReal > &v)
 Copy from CuVector. This is defined in ../cudamatrix/cu-vector.h. More...
 
void Floor (const VectorBase< Real > &v, Real floor_val, MatrixIndexT *floored_count=nullptr)
 Applies floor to all elements. More...
 
void Ceiling (const VectorBase< Real > &v, Real ceil_val, MatrixIndexT *ceiled_count=nullptr)
 Applies ceiling to all elements. More...
 
void Pow (const VectorBase< Real > &v, Real power)
 
void ApplyLog ()
 Apply natural log to all elements. More...
 
void ApplyLogAndCopy (const VectorBase< Real > &v)
 Apply natural log to another vector and put result in *this. More...
 
void ApplyExp ()
 Apply exponential to each value in vector. More...
 
void ApplyAbs ()
 Take absolute value of each of the elements. More...
 
void ApplyFloor (Real floor_val, MatrixIndexT *floored_count=nullptr)
 Applies floor to all elements. More...
 
void ApplyCeiling (Real ceil_val, MatrixIndexT *ceiled_count=nullptr)
 Applies ceiling to all elements. More...
 
MatrixIndexT ApplyFloor (const VectorBase< Real > &floor_vec)
 Applies floor to all elements. Returns number of elements floored. More...
 
Real ApplySoftMax ()
 Apply soft-max to vector and return normalizer (log sum of exponentials). More...
 
Real ApplyLogSoftMax ()
 Applies log soft-max to vector and returns normalizer (log sum of exponentials). More...
 
void Tanh (const VectorBase< Real > &src)
 Sets each element of *this to the tanh of the corresponding element of "src". More...
 
void Sigmoid (const VectorBase< Real > &src)
 Sets each element of *this to the sigmoid function of the corresponding element of "src". More...
 
void ApplyPow (Real power)
 Take all elements of vector to a power. More...
 
void ApplyPowAbs (Real power, bool include_sign=false)
 Take the absolute value of all elements of a vector to a power. More...
 
Real Norm (Real p) const
 Compute the p-th norm of the vector. More...
 
bool ApproxEqual (const VectorBase< Real > &other, float tol=0.01) const
 Returns true if ((*this)-other).Norm(2.0) <= tol * (*this).Norm(2.0). More...
 
void InvertElements ()
 Invert all elements. More...
 
template<typename OtherReal >
void AddVec (const Real alpha, const VectorBase< OtherReal > &v)
 Add vector : *this = *this + alpha * rv (with casting between floats and doubles) More...
 
void AddVec2 (const Real alpha, const VectorBase< Real > &v)
 Add vector : *this = *this + alpha * rv^2 [element-wise squaring]. More...
 
template<typename OtherReal >
void AddVec2 (const Real alpha, const VectorBase< OtherReal > &v)
 Add vector : *this = *this + alpha * rv^2 [element-wise squaring], with casting between floats and doubles. More...
 
void AddMatVec (const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 Add matrix times vector : this <– beta*this + alpha*M*v. More...
 
void AddMatSvec (const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 This is as AddMatVec, except optimized for where v contains a lot of zeros. More...
 
void AddSpVec (const Real alpha, const SpMatrix< Real > &M, const VectorBase< Real > &v, const Real beta)
 Add symmetric positive definite matrix times vector: this <– beta*this + alpha*M*v. More...
 
void AddTpVec (const Real alpha, const TpMatrix< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 Add triangular matrix times vector: this <– beta*this + alpha*M*v. More...
 
void ReplaceValue (Real orig, Real changed)
 Set each element to y = (x == orig ? changed : x). More...
 
void MulElements (const VectorBase< Real > &v)
 Multiply element-by-element by another vector. More...
 
template<typename OtherReal >
void MulElements (const VectorBase< OtherReal > &v)
 Multiply element-by-element by another vector of different type. More...
 
void DivElements (const VectorBase< Real > &v)
 Divide element-by-element by a vector. More...
 
template<typename OtherReal >
void DivElements (const VectorBase< OtherReal > &v)
 Divide element-by-element by a vector of different type. More...
 
void Add (Real c)
 Add a constant to each element of a vector. More...
 
void AddVecVec (Real alpha, const VectorBase< Real > &v, const VectorBase< Real > &r, Real beta)
 Add element-by-element product of vectors: More...
 
void AddVecDivVec (Real alpha, const VectorBase< Real > &v, const VectorBase< Real > &r, Real beta)
 Add element-by-element quotient of two vectors. More...
 
void Scale (Real alpha)
 Multiplies all elements by this constant. More...
 
void MulTp (const TpMatrix< Real > &M, const MatrixTransposeType trans)
 Multiplies this vector by lower-triangular matrix: *this <– *this *M. More...
 
void Solve (const TpMatrix< Real > &M, const MatrixTransposeType trans)
 If trans == kNoTrans, solves M x = b, where b is the value of *this at input and x is the value of *this at output. More...
 
void CopyRowsFromMat (const MatrixBase< Real > &M)
 Performs a row stack of the matrix M. More...
 
template<typename OtherReal >
void CopyRowsFromMat (const MatrixBase< OtherReal > &M)
 
void CopyRowsFromMat (const CuMatrixBase< Real > &M)
 The following is implemented in ../cudamatrix/cu-matrix.cc. More...
 
void CopyColsFromMat (const MatrixBase< Real > &M)
 Performs a column stack of the matrix M. More...
 
void CopyRowFromMat (const MatrixBase< Real > &M, MatrixIndexT row)
 Extracts a row of the matrix M. More...
 
template<typename OtherReal >
void CopyRowFromMat (const MatrixBase< OtherReal > &M, MatrixIndexT row)
 Extracts a row of the matrix M with type conversion. More...
 
template<typename OtherReal >
void CopyRowFromSp (const SpMatrix< OtherReal > &S, MatrixIndexT row)
 Extracts a row of the symmetric matrix S. More...
 
template<typename OtherReal >
void CopyColFromMat (const MatrixBase< OtherReal > &M, MatrixIndexT col)
 Extracts a column of the matrix M. More...
 
void CopyDiagFromMat (const MatrixBase< Real > &M)
 Extracts the diagonal of the matrix M. More...
 
void CopyDiagFromPacked (const PackedMatrix< Real > &M)
 Extracts the diagonal of a packed matrix M; works for Sp or Tp. More...
 
void CopyDiagFromSp (const SpMatrix< Real > &M)
 Extracts the diagonal of a symmetric matrix. More...
 
void CopyDiagFromTp (const TpMatrix< Real > &M)
 Extracts the diagonal of a triangular matrix. More...
 
Real Max () const
 Returns the maximum value of any element, or -infinity for the empty vector. More...
 
Real Max (MatrixIndexT *index) const
 Returns the maximum value of any element, and the associated index. More...
 
Real Min () const
 Returns the minimum value of any element, or +infinity for the empty vector. More...
 
Real Min (MatrixIndexT *index) const
 Returns the minimum value of any element, and the associated index. More...
 
Real Sum () const
 Returns sum of the elements. More...
 
Real SumLog () const
 Returns sum of the logs of the elements. More...
 
void AddRowSumMat (Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
 Does *this = alpha * (sum of rows of M) + beta * *this. More...
 
void AddColSumMat (Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
 Does *this = alpha * (sum of columns of M) + beta * *this. More...
 
void AddDiagMat2 (Real alpha, const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans, Real beta=1.0)
 Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans), or *this = diag(M^T M) + beta * *this (if trans == kTrans). More...
 
void AddDiagMatMat (Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const MatrixBase< Real > &N, MatrixTransposeType transN, Real beta=1.0)
 Add the diagonal of a matrix product: *this = diag(M N), assuming the "trans" arguments are both kNoTrans; for transpose arguments, it behaves as you would expect. More...
 
Real LogSumExp (Real prune=-1.0) const
 Returns log(sum(exp())) without exp overflow If prune > 0.0, ignores terms less than the max - prune. More...
 
void Read (std::istream &in, bool binary, bool add=false)
 Reads from C++ stream (option to add to existing contents). More...
 
void Write (std::ostream &Out, bool binary) const
 Writes to C++ stream (option to write in binary). More...
 
template<>
void AddVec (const float alpha, const VectorBase< float > &rv)
 
template<>
void AddVec (const double alpha, const VectorBase< double > &rv)
 
template<>
void AddVec (const float alpha, const VectorBase< float > &v)
 
template<>
void AddVec (const double alpha, const VectorBase< double > &v)
 

Protected Member Functions

 ~VectorBase ()
 Destructor; does not deallocate memory, this is handled by child classes. More...
 
 VectorBase ()
 Empty initializer, corresponds to vector of zero size. More...
 
void CopyFromPtr (const Real *Data, MatrixIndexT sz)
 Load data into the vector: sz must match own size. More...
 
 KALDI_DISALLOW_COPY_AND_ASSIGN (VectorBase)
 

Protected Attributes

Real * data_
 data memory area More...
 
MatrixIndexT dim_
 dimension of vector More...
 

Friends

class VectorBase< double >
 
class VectorBase< float >
 
class CuVectorBase< Real >
 
class CuVector< Real >
 

Detailed Description

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

Provides a vector abstraction class.

This class provides a way to work with vectors in kaldi. It encapsulates basic operations and memory optimizations.

Definition at line 41 of file kaldi-vector.h.

Constructor & Destructor Documentation

◆ ~VectorBase()

~VectorBase ( )
inlineprotected

Destructor; does not deallocate memory, this is handled by child classes.

This destructor is protected so this object can only be deleted via a child.

Definition at line 376 of file kaldi-vector.h.

376 {}

◆ VectorBase()

VectorBase ( )
inlineexplicitprotected

Empty initializer, corresponds to vector of zero size.

Definition at line 379 of file kaldi-vector.h.

379  : data_(NULL), dim_(0) {
381  }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ASSERT_IS_FLOATING_TYPE(F)
Definition: kaldi-utils.h:137
Real * data_
data memory area
Definition: kaldi-vector.h:395

Member Function Documentation

◆ Add()

void Add ( Real  c)

Add a constant to each element of a vector.

Definition at line 956 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), AmSgmm2::ComponentLogLikes(), kaldi::ComputeCorrelation(), OnlinePreconditioner::ComputeZt(), OnlineNaturalGradient::ComputeZt(), IvectorExtractor::GetAcousticAuxfWeight(), LogisticRegression::GetLogPosteriors(), Plda::GetNormalizationFactor(), ConstantComponent::InitFromConfig(), ConstantFunctionComponent::InitFromConfig(), Plda::LogLikelihoodRatio(), main(), kaldi::nnet1::MomentStatistics(), OnlinePitchFeatureImpl::OnlinePitchFeatureImpl(), PdfPrior::PdfPrior(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlinePreconditioner::PreconditionDirectionsInternal(), OnlineNaturalGradient::PreconditionDirectionsInternal(), kaldi::ProcessWindow(), AccumDiagGmm::SmoothStats(), AccumDiagGmm::SmoothWithModel(), MleAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleAmSgmm2Updater::UpdateSubstateWeights(), MleAmSgmm2Updater::UpdateW(), MleAmSgmm2Updater::UpdateWGetStats(), and MleSgmm2SpeakerAccs::UpdateWithU().

956  {
957  for (MatrixIndexT i = 0; i < dim_; i++) {
958  data_[i] += c;
959  }
960 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ AddColSumMat()

void AddColSumMat ( Real  alpha,
const MatrixBase< Real > &  M,
Real  beta = 1.0 
)

Does *this = alpha * (sum of columns of M) + beta * *this.

Definition at line 734 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestAddColSumMat(), KlHmm::PropagateFnc(), kaldi::UnitTestAddColSumMatSpeed(), kaldi::UnitTestCuDiffLogSoftmax(), kaldi::UnitTestCuVectorAddColSumMat(), kaldi::UnitTestCuVectorAddColSumMatLarge(), and kaldi::UnitTestSimpleForVec().

734  {
735  KALDI_ASSERT(dim_ == M.NumRows());
736  MatrixIndexT num_cols = M.NumCols();
737 
738  // implement the function according to a dimension cutoff for computation efficiency
739  if (num_cols <= 64) {
740  for (MatrixIndexT i = 0; i < dim_; i++) {
741  double sum = 0.0;
742  const Real *src = M.RowData(i);
743  for (MatrixIndexT j = 0; j < num_cols; j++)
744  sum += src[j];
745  data_[i] = alpha * sum + beta * data_[i];
746  }
747  } else {
748  Vector<Real> ones(M.NumCols());
749  ones.Set(1.0);
750  this->AddMatVec(alpha, M, kNoTrans, ones, beta);
751  }
752 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
void AddMatVec(const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
Add matrix times vector : this <– beta*this + alpha*M*v.
Definition: kaldi-vector.cc:92
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddDiagMat2()

void AddDiagMat2 ( Real  alpha,
const MatrixBase< Real > &  M,
MatrixTransposeType  trans = kNoTrans,
Real  beta = 1.0 
)

Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans), or *this = diag(M^T M) + beta * *this (if trans == kTrans).

Definition at line 1304 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestAddDiagMat2(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), kaldi::SlidingWindowCmnInternal(), kaldi::UnitTestAddDiagMat2(), and kaldi::UnitTestCuDiffNormalizePerRow().

1306  {
1307  if (trans == kNoTrans) {
1308  KALDI_ASSERT(this->dim_ == M.NumRows());
1309  MatrixIndexT rows = this->dim_, cols = M.NumCols(),
1310  mat_stride = M.Stride();
1311  Real *data = this->data_;
1312  const Real *mat_data = M.Data();
1313  for (MatrixIndexT i = 0; i < rows; i++, mat_data += mat_stride, data++)
1314  *data = beta * *data + alpha * cblas_Xdot(cols,mat_data,1,mat_data,1);
1315  } else {
1316  KALDI_ASSERT(this->dim_ == M.NumCols());
1317  MatrixIndexT rows = M.NumRows(), cols = this->dim_,
1318  mat_stride = M.Stride();
1319  Real *data = this->data_;
1320  const Real *mat_data = M.Data();
1321  for (MatrixIndexT i = 0; i < cols; i++, mat_data++, data++)
1322  *data = beta * *data + alpha * cblas_Xdot(rows, mat_data, mat_stride,
1323  mat_data, mat_stride);
1324  }
1325 }
float cblas_Xdot(const int N, const float *const X, const int incX, const float *const Y, const int incY)
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddDiagMatMat()

void AddDiagMatMat ( Real  alpha,
const MatrixBase< Real > &  M,
MatrixTransposeType  transM,
const MatrixBase< Real > &  N,
MatrixTransposeType  transN,
Real  beta = 1.0 
)

Add the diagonal of a matrix product: *this = diag(M N), assuming the "trans" arguments are both kNoTrans; for transpose arguments, it behaves as you would expect.

Definition at line 1328 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), kaldi::UnitTestAddDiagMatMat(), kaldi::UnitTestCuDiffNormalizePerRow(), and kaldi::UnitTestCuDiffSoftmax().

1332  {
1333  MatrixIndexT dim = this->dim_,
1334  M_col_dim = (transM == kTrans ? M.NumRows() : M.NumCols()),
1335  N_row_dim = (transN == kTrans ? N.NumCols() : N.NumRows());
1336  KALDI_ASSERT(M_col_dim == N_row_dim); // this is the dimension we sum over
1337  MatrixIndexT M_row_stride = M.Stride(), M_col_stride = 1;
1338  if (transM == kTrans) std::swap(M_row_stride, M_col_stride);
1339  MatrixIndexT N_row_stride = N.Stride(), N_col_stride = 1;
1340  if (transN == kTrans) std::swap(N_row_stride, N_col_stride);
1341 
1342  Real *data = this->data_;
1343  const Real *Mdata = M.Data(), *Ndata = N.Data();
1344  for (MatrixIndexT i = 0; i < dim; i++, Mdata += M_row_stride, Ndata += N_col_stride, data++) {
1345  *data = beta * *data + alpha * cblas_Xdot(M_col_dim, Mdata, M_col_stride, Ndata, N_row_stride);
1346  }
1347 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
float cblas_Xdot(const int N, const float *const X, const int incX, const float *const Y, const int incY)
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddMatSvec()

void AddMatSvec ( const Real  alpha,
const MatrixBase< Real > &  M,
const MatrixTransposeType  trans,
const VectorBase< Real > &  v,
const Real  beta 
)

This is as AddMatVec, except optimized for where v contains a lot of zeros.

Definition at line 105 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and kaldi::UnitTestVecmul().

109  {
110  KALDI_ASSERT((trans == kNoTrans && M.NumCols() == v.dim_ && M.NumRows() == dim_)
111  || (trans == kTrans && M.NumRows() == v.dim_ && M.NumCols() == dim_));
112  KALDI_ASSERT(&v != this);
113  Xgemv_sparsevec(trans, M.NumRows(), M.NumCols(), alpha, M.Data(), M.Stride(),
114  v.Data(), 1, beta, data_, 1);
115  return;
116  /*
117  MatrixIndexT this_dim = this->dim_, v_dim = v.dim_,
118  M_stride = M.Stride();
119  Real *this_data = this->data_;
120  const Real *M_data = M.Data(), *v_data = v.data_;
121  if (beta != 1.0) this->Scale(beta);
122  if (trans == kNoTrans) {
123  for (MatrixIndexT i = 0; i < v_dim; i++) {
124  Real v_i = v_data[i];
125  if (v_i == 0.0) continue;
126  // Add to *this, the i'th column of the Matrix, times v_i.
127  cblas_Xaxpy(this_dim, v_i * alpha, M_data + i, M_stride, this_data, 1);
128  }
129  } else { // The transposed case is slightly more efficient, I guess.
130  for (MatrixIndexT i = 0; i < v_dim; i++) {
131  Real v_i = v.data_[i];
132  if (v_i == 0.0) continue;
133  // Add to *this, the i'th row of the Matrix, times v_i.
134  cblas_Xaxpy(this_dim, v_i * alpha,
135  M_data + (i * M_stride), 1, this_data, 1);
136  }
137  }*/
138 }
void Xgemv_sparsevec(MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, Real alpha, const Real *Mdata, MatrixIndexT stride, const Real *xdata, MatrixIndexT incX, Real beta, Real *ydata, MatrixIndexT incY)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddMatVec()

void AddMatVec ( const Real  alpha,
const MatrixBase< Real > &  M,
const MatrixTransposeType  trans,
const VectorBase< Real > &  v,
const Real  beta 
)

Add matrix times vector : this <– beta*this + alpha*M*v.

Calls BLAS GEMV.

Definition at line 92 of file kaldi-vector.cc.

Referenced by OnlineIvectorEstimationStats::AccStats(), MleSgmm2SpeakerAccs::AccumulateFromPosteriors(), LdaEstimate::AddMeanOffset(), kaldi::ApplyAffineTransform(), ApplyFmllrXform(), VectorBase< float >::ApplyPow(), Fmpe::ApplyProjection(), Plda::ApplyTransform(), IvectorExtractorStats::CommitStatsForWPoint(), AmSgmm2::ComponentLogLikes(), MfccComputer::Compute(), kaldi::ComputeAmGmmFeatureDeriv(), Plda::ComputeDerivedVars(), AmSgmm2::ComputeFmllrPreXform(), MleAmSgmm2Updater::ComputeSMeans(), FmllrRawAccs::ConvertToSimpleStats(), kaldi::CuVectorUnitTestAddMatVec(), BasisFmllrEstimate::EstimateFmllrBasis(), FeatureTransformEstimateMulti::EstimateTransformPart(), kaldi::generate_features(), IvectorExtractor::GetAcousticAuxfMean(), IvectorExtractor::GetAcousticAuxfWeight(), kaldi::GetFeatDeriv(), OnlineTransform::GetFrame(), IvectorExtractor::GetIvectorDistMean(), IvectorExtractor::GetIvectorDistWeight(), LogisticRegression::GetLogPosteriors(), IvectorExtractorStats::GetOrthogonalIvectorTransform(), RegtreeMllrDiagGmm::GetTransformedMeans(), FullGmm::LogLikelihoods(), DiagGmm::LogLikelihoods(), DiagGmm::LogLikelihoodsPreselect(), DecodableAmDiagGmmUnmapped::LogLikelihoodZeroBased(), DecodableAmDiagGmmRegtreeMllr::LogLikelihoodZeroBased(), main(), MleAmSgmm2Updater::RenormalizeV(), kaldi::SolveDoubleQuadraticMatrixProblem(), kaldi::SolveQuadraticProblem(), Plda::TransformIvector(), UnitTestEstimateLda(), kaldi::UnitTestMul(), kaldi::UnitTestPldaEstimation(), FmllrRawAccs::Update(), EbwAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleSgmm2SpeakerAccs::UpdateWithU(), and kaldi::VecMatVec().

96  {
97  KALDI_ASSERT((trans == kNoTrans && M.NumCols() == v.dim_ && M.NumRows() == dim_)
98  || (trans == kTrans && M.NumRows() == v.dim_ && M.NumCols() == dim_));
99  KALDI_ASSERT(&v != this);
100  cblas_Xgemv(trans, M.NumRows(), M.NumCols(), alpha, M.Data(), M.Stride(),
101  v.Data(), 1, beta, data_, 1);
102 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void cblas_Xgemv(MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, float alpha, const float *Mdata, MatrixIndexT stride, const float *xdata, MatrixIndexT incX, float beta, float *ydata, MatrixIndexT incY)

◆ AddRowSumMat()

void AddRowSumMat ( Real  alpha,
const MatrixBase< Real > &  M,
Real  beta = 1.0 
)

Does *this = alpha * (sum of rows of M) + beta * *this.

Definition at line 714 of file kaldi-vector.cc.

Referenced by CovarianceStats::AccStats(), PldaStats::AddSamples(), IvectorExtractorStats::CommitStatsForW(), VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestAddRowSumMat(), kaldi::EstPca(), LdaEstimate::GetStats(), main(), AmSgmm2::SplitSubstatesInGroup(), kaldi::TestOnlineCmnInput(), kaldi::UnitTestAddRowSumMatSpeed(), kaldi::UnitTestCuVectorAddRowSumMat(), kaldi::UnitTestCuVectorAddRowSumMatLarge(), UnitTestEstimateFullGmm(), EbwAmSgmm2Updater::Update(), MleAmSgmm2Updater::Update(), and kaldi::nnet2::UpdateHash().

714  {
715  KALDI_ASSERT(dim_ == M.NumCols());
716  MatrixIndexT num_rows = M.NumRows(), stride = M.Stride(), dim = dim_;
717  Real *data = data_;
718 
719  // implement the function according to a dimension cutoff for computation efficiency
720  if (num_rows <= 64) {
721  cblas_Xscal(dim, beta, data, 1);
722  const Real *m_data = M.Data();
723  for (MatrixIndexT i = 0; i < num_rows; i++, m_data += stride)
724  cblas_Xaxpy(dim, alpha, m_data, 1, data, 1);
725 
726  } else {
727  Vector<Real> ones(M.NumRows());
728  ones.Set(1.0);
729  this->AddMatVec(alpha, M, kTrans, ones, beta);
730  }
731 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
void cblas_Xscal(const int N, const float alpha, float *data, const int inc)
void AddMatVec(const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
Add matrix times vector : this <– beta*this + alpha*M*v.
Definition: kaldi-vector.cc:92
Real * data_
data memory area
Definition: kaldi-vector.h:395
void cblas_Xaxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddSpVec()

void AddSpVec ( const Real  alpha,
const SpMatrix< Real > &  M,
const VectorBase< Real > &  v,
const Real  beta 
)

Add symmetric positive definite matrix times vector: this <– beta*this + alpha*M*v.

Calls BLAS SPMV.

Definition at line 141 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), kaldi::CalBasisFmllrStepSize(), AmSgmm2::ComputePerFrameVars(), FullGmmNormal::CopyToFullGmm(), kaldi::CuVectorUnitTestAddSpVec(), kaldi::FmllrAuxfGradient(), kaldi::FmllrAuxFuncDiagGmm(), kaldi::FmllrInnerUpdate(), IvectorExtractor::GetAcousticAuxfMean(), FullGmm::GetComponentMean(), IvectorExtractor::GetIvectorDistribution(), PldaEstimator::GetStatsFromClassMeans(), main(), kaldi::MllrAuxFunction(), FullGmm::SetInvCovars(), FullGmm::SetInvCovarsAndMeans(), kaldi::SolveQuadraticProblem(), AmSgmm2::SplitSubstatesInGroup(), SpMatrix< float >::TopEigs(), kaldi::UnitTestLbfgs(), kaldi::UnitTestLinearCgd(), kaldi::UnitTestMul(), kaldi::UnitTestSolve(), MlltAccs::Update(), EbwAmSgmm2Updater::UpdatePhoneVectorsInternal(), and MleSgmm2SpeakerAccs::UpdateWithU().

144  {
145  KALDI_ASSERT(M.NumRows() == v.dim_ && dim_ == v.dim_);
146  KALDI_ASSERT(&v != this);
147  cblas_Xspmv(alpha, M.NumRows(), M.Data(), v.Data(), 1, beta, data_, 1);
148 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void cblas_Xspmv(const float alpha, const int num_rows, const float *Mdata, const float *v, const int v_inc, const float beta, float *y, const int y_inc)

◆ AddTpVec()

void AddTpVec ( const Real  alpha,
const TpMatrix< Real > &  M,
const MatrixTransposeType  trans,
const VectorBase< Real > &  v,
const Real  beta 
)

Add triangular matrix times vector: this <– beta*this + alpha*M*v.

Works even if rv == *this.

Definition at line 1263 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), FastNnetCombiner::ComputeCurrentNnet(), FastNnetCombiner::ComputeObjfAndGradient(), FullGmmNormal::Rand(), kaldi::UnitTestCuVectorAddTp(), kaldi::UnitTestCuVectorAddTpVec(), kaldi::UnitTestMul(), and kaldi::UnitTestTriVecSolver().

1266  {
1267  KALDI_ASSERT(dim_ == v.dim_ && dim_ == M.NumRows());
1268  if (beta == 0.0) {
1269  if (&v != this) CopyFromVec(v);
1270  MulTp(M, trans);
1271  if (alpha != 1.0) Scale(alpha);
1272  } else {
1273  Vector<Real> tmp(v);
1274  tmp.MulTp(M, trans);
1275  if (beta != 1.0) Scale(beta); // *this <-- beta * *this
1276  AddVec(alpha, tmp); // *this += alpha * M * v
1277  }
1278 }
void MulTp(const TpMatrix< Real > &M, const MatrixTransposeType trans)
Multiplies this vector by lower-triangular matrix: *this <– *this *M.
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
void Scale(Real alpha)
Multiplies all elements by this constant.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...

◆ AddVec() [1/5]

void AddVec ( const float  alpha,
const VectorBase< float > &  rv 
)

◆ AddVec() [2/5]

void AddVec< double > ( const double  alpha,
const VectorBase< double > &  rv 
)

◆ AddVec() [3/5]

void AddVec ( const float  alpha,
const VectorBase< float > &  v 
)

Definition at line 75 of file kaldi-vector.cc.

76  {
77  KALDI_ASSERT(dim_ == v.dim_);
78  KALDI_ASSERT(&v != this);
79  cblas_Xaxpy(dim_, alpha, v.Data(), 1, data_, 1);
80 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * Data()
Returns a pointer to the start of the vector&#39;s data.
Definition: kaldi-vector.h:70
Real * data_
data memory area
Definition: kaldi-vector.h:395
void cblas_Xaxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddVec() [4/5]

void AddVec ( const double  alpha,
const VectorBase< double > &  v 
)

Definition at line 84 of file kaldi-vector.cc.

85  {
86  KALDI_ASSERT(dim_ == v.dim_);
87  KALDI_ASSERT(&v != this);
88  cblas_Xaxpy(dim_, alpha, v.Data(), 1, data_, 1);
89 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
void cblas_Xaxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddVec() [5/5]

void AddVec ( const Real  alpha,
const VectorBase< OtherReal > &  v 
)

Add vector : *this = *this + alpha * rv (with casting between floats and doubles)

Definition at line 1044 of file kaldi-vector.cc.

Referenced by OptimizeLbfgs< Real >::AcceptStep(), OnlineIvectorEstimationStats::AccStats(), AccumFullGmm::AccumulateFromPosteriors(), FmllrRawAccs::AccumulateFromPosteriors(), AccumDiagGmm::AccumulateFromPosteriors(), MleAmSgmm2Accs::AccumulateFromPosteriors(), MleSgmm2SpeakerAccs::AccumulateFromPosteriors(), RestrictedAttentionComponent::Add(), AccumDiagGmm::Add(), IvectorExtractorStats::Add(), kaldi::ApplyCmvn(), VectorBase< float >::ApplyPow(), Fmpe::ApplyProjection(), VectorBase< float >::ApproxEqual(), IvectorExtractorStats::CommitStatsForM(), IvectorExtractorStats::CommitStatsForPrior(), AmSgmm2::ComponentLogLikes(), kaldi::ComputeAmGmmFeatureDeriv(), kaldi::ComputeAndSubtractMean(), PitchFrameInfo::ComputeBacktraces(), Fmpe::ComputeC(), kaldi::ComputeFeatureNormalizingTransform(), AmSgmm2::ComputeFmllrPreXform(), AmSgmm2::ComputeGammaI(), Sgmm2Project::ComputeLdaStats(), kaldi::ComputeLocalCost(), OptimizeLbfgs< Real >::ComputeNewDirection(), PldaEstimator::ComputeObjfPart2(), EbwAmSgmm2Updater::ComputePhoneVecStats(), BasisFmllrEstimate::ComputeTransform(), CompressedAffineXformStats::CopyFromAffineXformStats(), kaldi::DiagGmmToStats(), kaldi::EBWUpdateGaussian(), kaldi::FmllrInnerUpdate(), kaldi::GenRandStats(), kaldi::GetFeatureMeanAndVariance(), IvectorExtractor::GetIvectorDistribution(), GetLogLikeTest(), PldaEstimator::GetStatsFromClassMeans(), AmSgmm2::GetSubstateSpeakerMean(), kaldi::LinearCgd(), Plda::LogLikelihoodRatio(), main(), FullGmm::Merge(), DiagGmm::merged_components_logdet(), FullGmm::MergedComponentsLogdet(), SoftmaxComponent::MixUp(), kaldi::operator>>(), OnlineCmnInput::OutputFrame(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), kaldi::nnet2::PrintPriorDiagnostics(), kaldi::nnet3::PrintPriorDiagnostics(), DeltaFeatures::Process(), ShiftedDeltaFeatures::Process(), AccumFullGmm::Read(), LdaEstimate::Read(), OptimizeLbfgs< Real >::Restart(), kaldi::SlidingWindowCmnInternal(), Plda::SmoothWithinClassCovariance(), kaldi::SolveQuadraticProblem(), RestrictedAttentionComponent::StoreStats(), kaldi::TestClusterKMeansVector(), kaldi::TestOnlineCmnInput(), SpMatrix< float >::TopEigs(), kaldi::TypeOneUsage(), kaldi::TypeThreeUsage(), kaldi::UnitTestAddDiagMat2(), kaldi::UnitTestAddDiagMatMat(), kaldi::UnitTestAddDiagVecMat(), kaldi::UnitTestAddVecCross(), kaldi::UnitTestCuVectorAddColSumMat(), kaldi::UnitTestCuVectorAddColSumMatLarge(), kaldi::UnitTestCuVectorAddRowSumMat(), kaldi::UnitTestCuVectorAddRowSumMatLarge(), kaldi::UnitTestCuVectorAddVec(), UnitTestEstimateDiagGmm(), UnitTestEstimateLda(), kaldi::UnitTestEstimateMmieDiagGmm(), kaldi::UnitTestLbfgs(), kaldi::UnitTestLinearCgd(), kaldi::UnitTestSparseVectorAddToVec(), kaldi::UpdateEbwDiagGmm(), EbwAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleAmSgmm2Updater::UpdatePhoneVectorsInternal(), PldaUnsupervisedAdaptor::UpdatePlda(), EbwAmSgmm2Updater::UpdateU(), MleAmSgmm2Updater::UpdateU(), EbwAmSgmm2Updater::UpdateW(), and MleSgmm2SpeakerAccs::UpdateWithU().

1044  {
1045  KALDI_ASSERT(dim_ == v.dim_);
1046  // remove __restrict__ if it causes compilation problems.
1047  Real *__restrict__ data = data_;
1048  OtherReal *__restrict__ other_data = v.data_;
1049  MatrixIndexT dim = dim_;
1050  if (alpha != 1.0)
1051  for (MatrixIndexT i = 0; i < dim; i++)
1052  data[i] += alpha * other_data[i];
1053  else
1054  for (MatrixIndexT i = 0; i < dim; i++)
1055  data[i] += other_data[i];
1056 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddVec2() [1/2]

void AddVec2 ( const Real  alpha,
const VectorBase< Real > &  v 
)

◆ AddVec2() [2/2]

void AddVec2 ( const Real  alpha,
const VectorBase< OtherReal > &  v 
)

Add vector : *this = *this + alpha * rv^2 [element-wise squaring], with casting between floats and doubles.

Definition at line 1065 of file kaldi-vector.cc.

1065  {
1066  KALDI_ASSERT(dim_ == v.dim_);
1067  // remove __restrict__ if it causes compilation problems.
1068  Real *__restrict__ data = data_;
1069  OtherReal *__restrict__ other_data = v.data_;
1070  MatrixIndexT dim = dim_;
1071  if (alpha != 1.0)
1072  for (MatrixIndexT i = 0; i < dim; i++)
1073  data[i] += alpha * other_data[i] * other_data[i];
1074  else
1075  for (MatrixIndexT i = 0; i < dim; i++)
1076  data[i] += other_data[i] * other_data[i];
1077 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddVecDivVec()

void AddVecDivVec ( Real  alpha,
const VectorBase< Real > &  v,
const VectorBase< Real > &  r,
Real  beta 
)

Add element-by-element quotient of two vectors.

this <—- alpha*v/r + beta*this

Definition at line 1034 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), main(), and kaldi::UnitTestSimpleForVec().

1035  {
1036  KALDI_ASSERT((dim_ == v.dim_ && dim_ == rr.dim_));
1037  for (MatrixIndexT i = 0; i < dim_; i++) {
1038  data_[i] = alpha * v.data_[i]/rr.data_[i] + beta * data_[i] ;
1039  }
1040 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddVecVec()

void AddVecVec ( Real  alpha,
const VectorBase< Real > &  v,
const VectorBase< Real > &  r,
Real  beta 
)

Add element-by-element product of vectors:

Definition at line 1000 of file kaldi-vector.cc.

Referenced by FmllrRawAccs::AccumulateFromPosteriors(), VectorBase< float >::ApplyPow(), MleAmSgmm2Accs::CommitStatsForSpk(), kaldi::ComputeAmGmmFeatureDeriv(), kaldi::ComputeLocalCost(), OptimizeLbfgs< Real >::ComputeNewDirection(), kaldi::CuVectorUnitTestAddVecVec(), kaldi::ExtendWaveWithSilence(), kaldi::GetFeatDeriv(), and BatchNormComponent::Info().

1001  {
1002  KALDI_ASSERT(v.data_ != this->data_ && r.data_ != this->data_);
1003  // We pretend that v is a band-diagonal matrix.
1004  KALDI_ASSERT(dim_ == v.dim_ && dim_ == r.dim_);
1005  cblas_Xgbmv(kNoTrans, dim_, dim_, 0, 0, alpha, v.data_, 1,
1006  r.data_, 1, beta, this->data_, 1);
1007 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void cblas_Xgbmv(MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, MatrixIndexT num_below, MatrixIndexT num_above, float alpha, const float *Mdata, MatrixIndexT stride, const float *xdata, MatrixIndexT incX, float beta, float *ydata, MatrixIndexT incY)

◆ ApplyAbs()

void ApplyAbs ( )

Take absolute value of each of the elements.

Definition at line 807 of file kaldi-vector.cc.

Referenced by kaldi::CuVectorUnitTestSum(), kaldi::nnet3::PrintPriorDiagnostics(), kaldi::nnet2::PrintPriorDiagnostics(), VectorBase< float >::Range(), and kaldi::UnitTestTopEigs().

807  {
808  for (MatrixIndexT i = 0; i < dim_; i++) { data_[i] = std::abs(data_[i]); }
809 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ ApplyCeiling()

void ApplyCeiling ( Real  ceil_val,
MatrixIndexT ceiled_count = nullptr 
)
inline

Applies ceiling to all elements.

Returns number of elements changed in ceiled_count if it is non-null.

Definition at line 155 of file kaldi-vector.h.

Referenced by kaldi::CuVectorUnitTestApplyCeiling(), FeatureTransformEstimate::EstimateInternal(), and kaldi::UnitTestFloorCeiling().

155  {
156  this->Ceiling(*this, ceil_val, ceiled_count);
157  };
void Ceiling(const VectorBase< Real > &v, Real ceil_val, MatrixIndexT *ceiled_count=nullptr)
Applies ceiling to all elements.

◆ ApplyExp()

◆ ApplyFloor() [1/2]

◆ ApplyFloor() [2/2]

MatrixIndexT ApplyFloor ( const VectorBase< Real > &  floor_vec)

Applies floor to all elements. Returns number of elements floored.

Definition at line 854 of file kaldi-vector.cc.

854  {
855  KALDI_ASSERT(floor_vec.Dim() == dim_);
856  MatrixIndexT num_floored = 0;
857  for (MatrixIndexT i = 0; i < dim_; i++) {
858  if (data_[i] < floor_vec(i)) {
859  data_[i] = floor_vec(i);
860  num_floored++;
861  }
862  }
863  return num_floored;
864 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyLog()

void ApplyLog ( )

Apply natural log to all elements.

Throw if any element of the vector is negative (but doesn't complain about zero; the log will be -infinity

Definition at line 783 of file kaldi-vector.cc.

Referenced by AmSgmm2::ComponentLogLikes(), FbankComputer::Compute(), kaldi::FrameLevelLpp(), IvectorExtractor::GetAcousticAuxfWeight(), PdfPrior::PdfPrior(), VectorBase< float >::Range(), LogisticRegression::ScalePriors(), and MleSgmm2SpeakerAccs::UpdateWithU().

783  {
784  for (MatrixIndexT i = 0; i < dim_; i++) {
785  if (data_[i] < 0.0)
786  KALDI_ERR << "Trying to take log of a negative number.";
787  data_[i] = Log(data_[i]);
788  }
789 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ ApplyLogAndCopy()

void ApplyLogAndCopy ( const VectorBase< Real > &  v)

Apply natural log to another vector and put result in *this.

Definition at line 792 of file kaldi-vector.cc.

Referenced by VectorBase< float >::Range(), and kaldi::UnitTestSimple().

792  {
793  KALDI_ASSERT(dim_ == v.Dim());
794  for (MatrixIndexT i = 0; i < dim_; i++) {
795  data_[i] = Log(v(i));
796  }
797 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyLogSoftMax()

Real ApplyLogSoftMax ( )

Applies log soft-max to vector and returns normalizer (log sum of exponentials).

This is the same as: $ x(i) = x(i) - log(\sum_i exp(x(i))) $

Definition at line 877 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyCeiling(), and kaldi::UnitTestSimpleForVec().

877  {
878  Real max = this->Max(), sum = 0.0;
879  for (MatrixIndexT i = 0; i < dim_; i++) {
880  sum += Exp((data_[i] -= max));
881  }
882  sum = Log(sum);
883  this->Add(-1.0 * sum);
884  return max + sum;
885 }
double Exp(double x)
Definition: kaldi-math.h:83
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.
Real * data_
data memory area
Definition: kaldi-vector.h:395
void Add(Real c)
Add a constant to each element of a vector.

◆ ApplyPow()

◆ ApplyPowAbs()

void ApplyPowAbs ( Real  power,
bool  include_sign = false 
)

Take the absolute value of all elements of a vector to a power.

Include the sign of the input element if include_sign == true. If power is negative and the input value is zero, the output is set zero.

Definition at line 479 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and kaldi::UnitTestPowerAbs().

479  {
480  if (power == 1.0)
481  for (MatrixIndexT i = 0; i < dim_; i++)
482  data_[i] = (include_sign && data_[i] < 0 ? -1 : 1) * std::abs(data_[i]);
483  if (power == 2.0) {
484  for (MatrixIndexT i = 0; i < dim_; i++)
485  data_[i] = (include_sign && data_[i] < 0 ? -1 : 1) * data_[i] * data_[i];
486  } else if (power == 0.5) {
487  for (MatrixIndexT i = 0; i < dim_; i++) {
488  data_[i] = (include_sign && data_[i] < 0 ? -1 : 1) * std::sqrt(std::abs(data_[i]));
489  }
490  } else if (power < 0.0) {
491  for (MatrixIndexT i = 0; i < dim_; i++) {
492  data_[i] = (data_[i] == 0.0 ? 0.0 : pow(std::abs(data_[i]), power));
493  data_[i] *= (include_sign && data_[i] < 0 ? -1 : 1);
494  if (data_[i] == HUGE_VAL) { // HUGE_VAL is what errno returns on error.
495  KALDI_ERR << "Could not raise element " << i << "to power "
496  << power << ": returned value = " << data_[i];
497  }
498  }
499  } else {
500  for (MatrixIndexT i = 0; i < dim_; i++) {
501  data_[i] = (include_sign && data_[i] < 0 ? -1 : 1) * pow(std::abs(data_[i]), power);
502  if (data_[i] == HUGE_VAL) { // HUGE_VAL is what errno returns on error.
503  KALDI_ERR << "Could not raise element " << i << "to power "
504  << power << ": returned value = " << data_[i];
505  }
506  }
507  }
508 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ ApplySoftMax()

Real ApplySoftMax ( )

Apply soft-max to vector and return normalizer (log sum of exponentials).

This is the same as: $ x(i) = exp(x(i)) / \sum_i exp(x(i)) $

Definition at line 867 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyCeiling(), Fmpe::ApplyProjection(), Fmpe::ApplyProjectionReverse(), IvectorExtractorStats::CommitStatsForWPoint(), FullGmm::ComponentPosteriors(), DiagGmm::ComponentPosteriors(), AmSgmm2::ComputeFmllrPreXform(), kaldi::CuVectorUnitTestApplySoftMax(), IvectorExtractor::GetIvectorDistWeight(), main(), and EbwAmSgmm2Updater::UpdatePhoneVectorsInternal().

867  {
868  Real max = this->Max(), sum = 0.0;
869  for (MatrixIndexT i = 0; i < dim_; i++) {
870  sum += (data_[i] = Exp(data_[i] - max));
871  }
872  this->Scale(1.0 / sum);
873  return max + Log(sum);
874 }
double Exp(double x)
Definition: kaldi-math.h:83
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.
void Scale(Real alpha)
Multiplies all elements by this constant.
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ ApproxEqual()

bool ApproxEqual ( const VectorBase< Real > &  other,
float  tol = 0.01 
) const

Returns true if ((*this)-other).Norm(2.0) <= tol * (*this).Norm(2.0).

Definition at line 556 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), kaldi::ApproxEqual(), AccumDiagGmm::AssertEqual(), kaldi::AssertEqual(), kaldi::CuVectorUnitTestCopyDiagFromPacked(), FmllrRawAccs::DataHasChanged(), FmllrDiagGmmAccs::DataHasChanged(), and kaldi::UnitTestNorm().

556  {
557  if (dim_ != other.dim_) KALDI_ERR << "ApproxEqual: size mismatch "
558  << dim_ << " vs. " << other.dim_;
559  KALDI_ASSERT(tol >= 0.0);
560  if (tol != 0.0) {
561  Vector<Real> tmp(*this);
562  tmp.AddVec(-1.0, other);
563  return (tmp.Norm(2.0) <= static_cast<Real>(tol) * this->Norm(2.0));
564  } else { // Test for exact equality.
565  const Real *data = data_;
566  const Real *other_data = other.data_;
567  for (MatrixIndexT dim = dim_, i = 0; i < dim; i++)
568  if (data[i] != other_data[i]) return false;
569  return true;
570  }
571 }
Real Norm(Real p) const
Compute the p-th norm of the vector.
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Ceiling()

void Ceiling ( const VectorBase< Real > &  v,
Real  ceil_val,
MatrixIndexT ceiled_count = nullptr 
)

Applies ceiling to all elements.

Returns number of elements changed in ceiled_count if it is non-null.

Definition at line 833 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyCeiling(), and VectorBase< float >::Range().

833  {
834  KALDI_ASSERT(dim_ == v.dim_);
835  if (ceiled_count == nullptr) {
836  for (MatrixIndexT i = 0; i < dim_; i++) {
837  data_[i] = std::min(v.data_[i], ceil_val);
838  }
839  } else {
840  MatrixIndexT num_changed = 0;
841  for (MatrixIndexT i = 0; i < dim_; i++) {
842  if (v.data_[i] > ceil_val) {
843  data_[i] = ceil_val;
844  num_changed++;
845  } else {
846  data_[i] = v.data_[i];
847  }
848  }
849  *ceiled_count = num_changed;
850  }
851 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyColFromMat()

template void CopyColFromMat ( const MatrixBase< OtherReal > &  M,
MatrixIndexT  col 
)

Extracts a column of the matrix M.

Definition at line 656 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), kaldi::ComputeVadEnergy(), kaldi::generate_features(), kaldi::IncreaseTransformDimension(), main(), kaldi::TestOnlineLdaInput(), TestSgmm2PreXform(), kaldi::UnitTestAddDiagVecMat(), kaldi::UnitTestRow(), kaldi::UnitTestSimpleForVec(), kaldi::UnitTestSnipEdges(), and kaldi::UnitTestSpliceRows().

656  {
657  KALDI_ASSERT(col < mat.NumCols());
658  KALDI_ASSERT(dim_ == mat.NumRows());
659  for (MatrixIndexT i = 0; i < dim_; i++)
660  data_[i] = mat(i, col);
661  // can't do this very efficiently so don't really bother. could improve this though.
662 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyColsFromMat()

void CopyColsFromMat ( const MatrixBase< Real > &  M)

Performs a column stack of the matrix M.

Definition at line 390 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and kaldi::UnitTestSpliceRows().

390  {
391  KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
392 
393  Real* inc_data = data_;
394  const MatrixIndexT cols = mat.NumCols(), rows = mat.NumRows(), stride = mat.Stride();
395  const Real *mat_inc_data = mat.Data();
396 
397  for (MatrixIndexT i = 0; i < cols; i++) {
398  for (MatrixIndexT j = 0; j < rows; j++) {
399  inc_data[j] = mat_inc_data[j*stride];
400  }
401  mat_inc_data++;
402  inc_data += rows;
403  }
404 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyDiagFromMat()

void CopyDiagFromMat ( const MatrixBase< Real > &  M)

Extracts the diagonal of the matrix M.

Definition at line 674 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), kaldi::CuVectorUnitTestCopyDiagFromMat(), kaldi::UnitTestAddDiagMat2(), kaldi::UnitTestAddDiagMatMat(), kaldi::UnitTestSpliceRows(), and kaldi::UnitTestTopEigs().

674  {
675  KALDI_ASSERT(dim_ == std::min(M.NumRows(), M.NumCols()));
676  cblas_Xcopy(dim_, M.Data(), M.Stride() + 1, data_, 1);
677 }
void cblas_Xcopy(const int N, const float *X, const int incX, float *Y, const int incY)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyDiagFromPacked()

void CopyDiagFromPacked ( const PackedMatrix< Real > &  M)

Extracts the diagonal of a packed matrix M; works for Sp or Tp.

Definition at line 680 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), VectorBase< float >::CopyDiagFromSp(), VectorBase< float >::CopyDiagFromTp(), DiagGmm::CopyFromFullGmm(), kaldi::CuVectorUnitTestCopyDiagFromPacked(), and SpMatrix< float >::Eig().

680  {
681  KALDI_ASSERT(dim_ == M.NumCols());
682  for (MatrixIndexT i = 0; i < dim_; i++)
683  data_[i] = M(i, i);
684  // could make this more efficient.
685 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyDiagFromSp()

void CopyDiagFromSp ( const SpMatrix< Real > &  M)
inline

Extracts the diagonal of a symmetric matrix.

Definition at line 309 of file kaldi-vector.h.

Referenced by kaldi::SolveQuadraticMatrixProblem(), kaldi::SolveQuadraticProblem(), and SpMatrix< float >::TopEigs().

309 { CopyDiagFromPacked(M); }
void CopyDiagFromPacked(const PackedMatrix< Real > &M)
Extracts the diagonal of a packed matrix M; works for Sp or Tp.

◆ CopyDiagFromTp()

void CopyDiagFromTp ( const TpMatrix< Real > &  M)
inline

Extracts the diagonal of a triangular matrix.

Definition at line 312 of file kaldi-vector.h.

312 { CopyDiagFromPacked(M); }
void CopyDiagFromPacked(const PackedMatrix< Real > &M)
Extracts the diagonal of a packed matrix M; works for Sp or Tp.

◆ CopyFromPacked()

template void CopyFromPacked ( const PackedMatrix< OtherReal > &  M)

Copy data from a SpMatrix or TpMatrix (must match own size).

Definition at line 237 of file kaldi-vector.cc.

Referenced by VectorBase< float >::Range().

237  {
238  SubVector<OtherReal> v(M);
239  this->CopyFromVec(v);
240 }
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).

◆ CopyFromPtr()

void CopyFromPtr ( const Real *  Data,
MatrixIndexT  sz 
)
protected

Load data into the vector: sz must match own size.

Load data into the vector.

Definition at line 249 of file kaldi-vector.cc.

Referenced by VectorBase< float >::VectorBase().

249  {
250  KALDI_ASSERT(dim_ == sz);
251  std::memcpy(this->data_, data, Dim() * sizeof(Real));
252 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyFromVec() [1/3]

void CopyFromVec ( const VectorBase< Real > &  v)

Copy data from another vector (must match own size).

Copy data from another vector.

Definition at line 228 of file kaldi-vector.cc.

Referenced by OptimizeLbfgs< Real >::AcceptStep(), RegtreeMllrDiagGmmAccs::AccumulateForGaussian(), RegtreeMllrDiagGmmAccs::AccumulateForGmm(), AccumFullGmm::AccumulateFromPosteriors(), BatchedXvectorComputer::AddChunkToBatch(), kaldi::ApplyAffineTransform(), Fmpe::ApplyC(), Plda::ApplyTransform(), kaldi::ClusterGaussiansToUbm(), kaldi::nnet2::CombineNnets(), kaldi::nnet2::CombineNnetsA(), FullGmm::ComponentPosteriors(), DiagGmm::ComponentPosteriors(), SpectrogramComputer::Compute(), kaldi::ComputeAndSubtractMean(), OnlinePreconditioner::ComputeEt(), OnlineNaturalGradient::ComputeEt(), kaldi::ComputeFeatureNormalizingTransform(), OnlineGenericBaseFeature< C >::ComputeFeatures(), OnlineLdaInput::ComputeNextRemainder(), EbwAmSgmm2Updater::ComputePhoneVecStats(), OnlineCmvn::ComputeStatsForFrame(), LstmNonlinearityComponent::ConsolidateMemory(), FmllrRawAccs::ConvertToSimpleStats(), kaldi::ConvolveSignals(), DiagGmmNormal::CopyFromDiagGmm(), FullGmmNormal::CopyFromFullGmm(), CuVectorBase< float >::CopyToVec(), kaldi::CuVectorUnitTestCopyCross2(), DiscriminativeExampleSplitter::DoExcise(), kaldi::EBWUpdateGaussian(), DecodableNnetSimple::EnsureFrameIsComputed(), OnlinePitchFeatureImpl::ExtractFrame(), kaldi::ExtractObjectRange(), kaldi::ExtractRowRangeWithPadding(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), kaldi::FilterMatrixRows(), FullGmm::GetComponentMean(), FullGmm::GetCovarsAndMeans(), kaldi::GetFeatureMeanAndVariance(), OnlineGenericBaseFeature< C >::GetFrame(), OnlineMatrixFeature::GetFrame(), OnlineIvectorFeature::GetFrame(), OnlineTransform::GetFrame(), OnlineCacheFeature::GetFrame(), IvectorExtractor::GetIvectorDistribution(), RegtreeFmllrDiagGmm::GetLogDets(), LogisticRegression::GetLogPosteriors(), FullGmm::GetMeans(), LogisticRegression::GetObjfAndGrad(), DecodableNnetSimple::GetOutputForFrame(), DecodableNnetSimpleLooped::GetOutputForFrame(), SentenceAveragingComponent::GetParams(), OnlineCmvn::GetState(), AmSgmm2::GetSubstateMean(), AmSgmm2::GetVarScaledSubstateSpeakerMean(), kaldi::IsmoothStatsDiagGmm(), IvectorExtractor::IvectorExtractor(), kaldi::LinearCgd(), FullGmm::LogLikelihoods(), DiagGmm::LogLikelihoods(), DiagGmm::LogLikelihoodsPreselect(), main(), DiagGmm::merged_components_logdet(), FullGmm::MergedComponentsLogdet(), DiagGmm::MergeKmeans(), SoftmaxComponent::MixUp(), Vector< float >::operator=(), OnlineCmnInput::OutputFrame(), OnlinePreconditionerSimple::PreconditionDirections(), OnlineNaturalGradientSimple::PreconditionDirections(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), kaldi::nnet3::ProcessFile(), kaldi::nnet2::ProcessFile(), FullGmmNormal::Rand(), VectorBase< float >::Range(), OnlineVectorSource::Read(), kaldi::RealFftInefficient(), OptimizeLbfgs< Real >::Restart(), kaldi::ReverseFrames(), kaldi::nnet3::RunNnetComputation(), DiagGmm::SetComponentInvVar(), FullGmm::SetInvCovars(), kaldi::SlidingWindowCmnInternal(), kaldi::SolveQuadraticProblem(), OnlineLdaInput::SpliceFrames(), SpMatrix< float >::TopEigs(), Plda::TransformIvector(), kaldi::UnitTestAddDiagVecMat(), kaldi::UnitTestComplexFft(), kaldi::UnitTestCuVectorCopyFromVec(), kaldi::UnitTestDiagGmm(), UnitTestEstimateLda(), UnitTestFullGmm(), kaldi::UnitTestIoCross(), kaldi::UnitTestPower(), kaldi::UnitTestPowerAbs(), UnitTestReadWave(), kaldi::UnitTestRealFft(), kaldi::UnitTestRegtreeFmllrDiagGmm(), kaldi::UnitTestSimpleForVec(), kaldi::UnitTestSplitRadixComplexFft(), kaldi::UnitTestSplitRadixComplexFft2(), kaldi::UnitTestSplitRadixRealFft(), kaldi::UnitTestSubvector(), FmllrRawAccs::Update(), kaldi::UpdateEbwDiagGmm(), kaldi::UpdateEbwWeightsDiagGmm(), MleSgmm2SpeakerAccs::UpdateNoU(), PldaUnsupervisedAdaptor::UpdatePlda(), IvectorExtractorStats::UpdateProjection(), IvectorExtractorStats::UpdateVariances(), IvectorExtractorStats::UpdateWeight(), MleSgmm2SpeakerAccs::UpdateWithU(), Vector< float >::Vector(), ConstantComponent::Vectorize(), PerElementScaleComponent::Vectorize(), PerElementOffsetComponent::Vectorize(), ConstantFunctionComponent::Vectorize(), and NonlinearComponent::Write().

228  {
229  KALDI_ASSERT(Dim() == v.Dim());
230  if (data_ != v.data_) {
231  std::memcpy(this->data_, v.data_, dim_ * sizeof(Real));
232  }
233 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyFromVec() [2/3]

void CopyFromVec ( const VectorBase< OtherReal > &  v)

Copy data from another vector of different type (double vs. float)

Definition at line 256 of file kaldi-vector.cc.

256  {
257  KALDI_ASSERT(dim_ == other.Dim());
258  Real * __restrict__ ptr = data_;
259  const OtherReal * __restrict__ other_ptr = other.Data();
260  for (MatrixIndexT i = 0; i < dim_; i++)
261  ptr[i] = other_ptr[i];
262 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyFromVec() [3/3]

void CopyFromVec ( const CuVectorBase< OtherReal > &  v)

Copy from CuVector. This is defined in ../cudamatrix/cu-vector.h.

Definition at line 383 of file cu-vector.h.

383  {
384  cu.CopyToVec(this);
385 }

◆ CopyRowFromMat() [1/2]

void CopyRowFromMat ( const MatrixBase< Real > &  M,
MatrixIndexT  row 
)

Extracts a row of the matrix M.

Could also do this with this->Copy(M[row]).

Definition at line 407 of file kaldi-vector.cc.

Referenced by RegtreeFmllrDiagGmmAccs::AccumulateForGaussian(), RegtreeFmllrDiagGmmAccs::AccumulateForGmm(), VectorBase< float >::ApplyPow(), DiagGmm::GetComponentMean(), DiagGmm::GetComponentVariance(), LdaEstimate::GetStats(), main(), UnitTestEstimateDiagGmm(), kaldi::UnitTestEstimateMmieDiagGmm(), kaldi::UnitTestPosteriors(), kaldi::UnitTestRow(), and kaldi::UnitTestSpliceRows().

407  {
408  KALDI_ASSERT(row < mat.NumRows());
409  KALDI_ASSERT(dim_ == mat.NumCols());
410  const Real *mat_row = mat.RowData(row);
411  memcpy(data_, mat_row, sizeof(Real)*dim_);
412 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyRowFromMat() [2/2]

void CopyRowFromMat ( const MatrixBase< OtherReal > &  M,
MatrixIndexT  row 
)

Extracts a row of the matrix M with type conversion.

Definition at line 416 of file kaldi-vector.cc.

416  {
417  KALDI_ASSERT(row < mat.NumRows());
418  KALDI_ASSERT(dim_ == mat.NumCols());
419  const OtherReal *mat_row = mat.RowData(row);
420  for (MatrixIndexT i = 0; i < dim_; i++)
421  data_[i] = static_cast<Real>(mat_row[i]);
422 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyRowFromSp()

template void CopyRowFromSp ( const SpMatrix< OtherReal > &  S,
MatrixIndexT  row 
)

Extracts a row of the symmetric matrix S.

Definition at line 431 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and CompressedAffineXformStats::CopyFromAffineXformStats().

431  {
432  KALDI_ASSERT(row < sp.NumRows());
433  KALDI_ASSERT(dim_ == sp.NumCols());
434 
435  const OtherReal *sp_data = sp.Data();
436 
437  sp_data += (row*(row+1)) / 2; // takes us to beginning of this row.
438  MatrixIndexT i;
439  for (i = 0; i < row; i++) // copy consecutive elements.
440  data_[i] = static_cast<Real>(*(sp_data++));
441  for(; i < dim_; ++i, sp_data += i)
442  data_[i] = static_cast<Real>(*sp_data);
443 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyRowsFromMat() [1/3]

void CopyRowsFromMat ( const MatrixBase< Real > &  M)

Performs a row stack of the matrix M.

Definition at line 348 of file kaldi-vector.cc.

Referenced by BasisFmllrAccus::AccuGradientScatter(), FmllrSgmm2Accs::AccumulateForFmllrSubspace(), VectorBase< float >::ApplyPow(), LstmNonlinearityComponent::ConsolidateMemory(), kaldi::CuVectorUnitTestCopyFromMat(), FmllrRawAccs::GetAuxf(), LinearTransform::GetGradient(), LinearTransform::GetParams(), kaldi::nnet1::MomentStatistics(), LogisticRegression::TrainParameters(), kaldi::UnitTestSpliceRows(), LstmNonlinearityComponent::Vectorize(), and LinearComponent::Vectorize().

348  {
349  KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
350 
351  Real *inc_data = data_;
352  const MatrixIndexT cols = mat.NumCols(), rows = mat.NumRows();
353 
354  if (mat.Stride() == mat.NumCols()) {
355  memcpy(inc_data, mat.Data(), cols*rows*sizeof(Real));
356  } else {
357  for (MatrixIndexT i = 0; i < rows; i++) {
358  // copy the data to the propper position
359  memcpy(inc_data, mat.RowData(i), cols * sizeof(Real));
360  // set new copy position
361  inc_data += cols;
362  }
363  }
364 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyRowsFromMat() [2/3]

void CopyRowsFromMat ( const MatrixBase< OtherReal > &  M)

Definition at line 368 of file kaldi-vector.cc.

368  {
369  KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
370  Real *vec_data = data_;
371  const MatrixIndexT cols = mat.NumCols(),
372  rows = mat.NumRows();
373 
374  for (MatrixIndexT i = 0; i < rows; i++) {
375  const OtherReal *mat_row = mat.RowData(i);
376  for (MatrixIndexT j = 0; j < cols; j++) {
377  vec_data[j] = static_cast<Real>(mat_row[j]);
378  }
379  vec_data += cols;
380  }
381 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyRowsFromMat() [3/3]

void CopyRowsFromMat ( const CuMatrixBase< Real > &  M)

The following is implemented in ../cudamatrix/cu-matrix.cc.

Definition at line 2621 of file cu-matrix.cc.

2621  {
2622  KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
2623 #if HAVE_CUDA == 1
2624  if (CuDevice::Instantiate().Enabled()) {
2625  CuTimer tim;
2626  if (mat.Stride() == mat.NumCols()) {
2627  CU_SAFE_CALL(cudaMemcpyAsync(data_, mat.Data(), sizeof(Real)*dim_,
2628  cudaMemcpyDeviceToHost, cudaStreamPerThread));
2629  } else {
2630  // we could definitely do better than the following.
2631  Real* vec_data = data_;
2632  for (MatrixIndexT r = 0; r < mat.NumRows(); r++) {
2633  CU_SAFE_CALL(cudaMemcpyAsync(vec_data, mat.RowData(r),
2634  sizeof(Real) * mat.NumCols(), cudaMemcpyDeviceToHost,
2635  cudaStreamPerThread));
2636  vec_data += mat.NumCols();
2637  }
2638  }
2639  CU_SAFE_CALL(cudaStreamSynchronize(cudaStreamPerThread));
2640  CuDevice::Instantiate().AccuProfile("CuVectorBase::CopyRowsFromMat", tim);
2641  } else
2642 #endif
2643  {
2644  CopyRowsFromMat(mat.Mat());
2645  }
2646 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void CopyRowsFromMat(const MatrixBase< Real > &M)
Performs a row stack of the matrix M.

◆ Data() [1/2]

Real* Data ( )
inline

Returns a pointer to the start of the vector's data.

Definition at line 70 of file kaldi-vector.h.

Referenced by kaldi::AccCmvnStats(), SpMatrix< float >::AddDiagVec(), MatrixBase< float >::AddDiagVecMat(), SpMatrix< float >::AddMat2Sp(), SpMatrix< float >::AddMat2Vec(), MatrixBase< float >::AddMatDiagVec(), VectorBase< float >::AddMatSvec(), VectorBase< float >::AddMatVec(), kaldi::AddOuterProductPlusMinus(), VectorBase< float >::AddSpVec(), SparseVector< Real >::AddToVec(), VectorBase< float >::AddVec(), SpMatrix< float >::AddVec2(), SpMatrix< float >::AddVec2Sp(), MatrixBase< float >::AddVecToCols(), MatrixBase< float >::AddVecToRows(), MatrixBase< float >::AddVecVec(), SpMatrix< float >::AddVecVec(), kaldi::ComplexFft(), kaldi::ComplexFftRecursive(), kaldi::ComplexFt(), kaldi::nnet3::ComponentDotProducts(), SpectrogramComputer::Compute(), MfccComputer::Compute(), FbankComputer::Compute(), PlpComputer::Compute(), PitchFrameInfo::ComputeBacktraces(), OnlinePreconditioner::ComputeEt(), OnlineNaturalGradient::ComputeEt(), kaldi::ComputeLpc(), kaldi::ComputeVadEnergy(), MatrixBase< float >::CopyColFromVec(), MatrixBase< float >::CopyColsFromVec(), CompressedMatrix::CopyColToVec(), MatrixBase< float >::CopyDiagFromVec(), SparseVector< Real >::CopyElementsToVec(), SparseMatrix< float >::CopyElementsToVec(), CuVectorBase< float >::CopyFromVec(), PackedMatrix< float >::CopyFromVec(), VectorBase< float >::CopyFromVec(), MatrixBase< float >::CopyRowFromVec(), MatrixBase< float >::CopyRowsFromVec(), CuMatrixBase< float >::CopyRowsFromVec(), CompressedMatrix::CopyRowToVec(), CuVectorBase< float >::CopyToVec(), kaldi::Dither(), VectorBase< float >::DivElements(), OnlineSpeexEncoder::Encode(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), FullGmm::GaussianSelection(), DiagGmm::GaussianSelection(), AmSgmm2::GaussianSelection(), FullGmm::GaussianSelectionPreselect(), DiagGmm::GaussianSelectionPreselect(), OnlineCmvn::GetFrame(), MatrixBase< float >::LapackGesvd(), SoftmaxComponent::MixUp(), VectorBase< float >::MulElements(), SpMatrix< float >::Qr(), kaldi::nnet3::ReadVectorAsChar(), kaldi::RealFft(), kaldi::SelectLags(), SparseVector< Real >::SparseVector(), AmSgmm2::SplitSubstatesInGroup(), SubVector< Real >::SubVector(), kaldi::nnet3::SummarizeVector(), SpMatrix< float >::Tridiagonalize(), kaldi::UnitTestEigSp(), kaldi::UnitTestPldaEstimation(), kaldi::UnitTestSimpleForMat(), kaldi::UnitTestSplitRadixComplexFft(), kaldi::UnitTestSplitRadixRealFft(), kaldi::UnitTestSplitRadixRealFftSpeed(), kaldi::UnitTestTopEigs(), kaldi::VecSpVec(), kaldi::VecSvec(), VectorBase< float >::VectorBase(), kaldi::VecVec(), kaldi::nnet3::WriteVectorAsChar(), and kaldi::nnet3::time_height_convolution::ZeroBlankRows().

70 { return data_; }
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Data() [2/2]

const Real* Data ( ) const
inline

Returns a pointer to the start of the vector's data (const).

Definition at line 73 of file kaldi-vector.h.

73 { return data_; }
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Dim()

MatrixIndexT Dim ( ) const
inline

Returns the dimension of the vector.

Definition at line 64 of file kaldi-vector.h.

Referenced by kaldi::AccCmvnStats(), kaldi::AccCmvnStatsWrapper(), OnlineSpeexDecoder::AcceptSpeexBits(), OnlineSpeexEncoder::AcceptWaveform(), OnlineGenericBaseFeature< C >::AcceptWaveform(), SingleUtteranceNnet2DecoderThreaded::AcceptWaveform(), OnlinePitchFeatureImpl::AcceptWaveform(), NnetLdaStatsAccumulator::AccStatsFromOutput(), LdaEstimate::Accumulate(), AccumFullGmm::AccumulateForComponent(), AccumDiagGmm::AccumulateForComponent(), FmllrRawAccs::AccumulateForGmm(), kaldi::AccumulateForUtterance(), AccumDiagGmm::AccumulateFromDiag(), MlltAccs::AccumulateFromPosteriors(), AccumFullGmm::AccumulateFromPosteriors(), AccumDiagGmm::AccumulateFromPosteriors(), MleAmSgmm2Accs::AccumulateFromPosteriors(), MleSgmm2SpeakerAccs::AccumulateFromPosteriors(), FmllrDiagGmmAccs::AccumulateFromPosteriorsPreselect(), RestrictedAttentionComponent::Add(), VectorRandomizer::AddData(), SpMatrix< float >::AddDiagVec(), MatrixBase< float >::AddDiagVecMat(), SpMatrix< float >::AddMat2Vec(), MatrixBase< float >::AddMatDiagVec(), Nnet::AddNnet(), kaldi::nnet3::AddNnetComponents(), kaldi::AddNoise(), kaldi::AddOuterProductPlusMinus(), PldaUnsupervisedAdaptor::AddStats(), SparseVector< Real >::AddToVec(), SpMatrix< float >::AddVec2(), SpMatrix< float >::AddVec2Sp(), MatrixBase< float >::AddVecToCols(), MatrixBase< float >::AddVecToRows(), kaldi::AddVectorsOfUnequalLength(), kaldi::AddVectorsWithOffset(), MatrixBase< float >::AddVecVec(), SpMatrix< float >::AddVecVec(), DecodableNnetSimpleLooped::AdvanceChunk(), kaldi::AppendVector(), kaldi::AppendVectorToFeats(), kaldi::ApplyAffineTransform(), VectorBase< float >::ApplyFloor(), SpMatrix< float >::ApplyFloor(), ApplyFmllrXform(), VectorBase< float >::ApplyLogAndCopy(), Fmpe::ApplyProjection(), Fmpe::ApplyProjectionReverse(), AssertEqual(), MleAmSgmm2Accs::Check(), IvectorExtractorStats::CheckDims(), MleSgmm2SpeakerAccs::Clear(), kaldi::nnet2::CombineNnets(), kaldi::nnet2::CombineNnetsA(), IvectorExtractorStats::CommitStatsForM(), MleAmSgmm2Accs::CommitStatsForSpk(), kaldi::ComplexFft(), kaldi::ComplexFftRecursive(), kaldi::ComplexFt(), kaldi::nnet3::ComponentDotProducts(), Nnet::ComponentDotProducts(), FullGmm::ComponentLogLikelihood(), DiagGmm::ComponentLogLikelihood(), AmSgmm2::ComponentLogLikes(), DiagGmm::ComponentPosteriors(), SpectrogramComputer::Compute(), MelBanks::Compute(), MfccComputer::Compute(), FbankComputer::Compute(), OfflineFeatureTpl< F >::Compute(), PlpComputer::Compute(), kaldi::nnet3::ComputeAccuracy(), kaldi::ComputeAndProcessKaldiPitch(), PitchFrameInfo::ComputeBacktraces(), kaldi::ComputeEarlyReverbEnergy(), OnlinePreconditioner::ComputeEt(), OnlineNaturalGradient::ComputeEt(), AmSgmm2::ComputeFmllrPreXform(), AmSgmm2::ComputeGammaI(), kaldi::ComputeGconsts(), AmSgmm2::ComputeHsmFromModel(), kaldi::ComputeKaldiPitch(), kaldi::ComputeKaldiPitchFirstPass(), kaldi::ComputeLifterCoeffs(), kaldi::ComputeLocalCost(), kaldi::ComputeLpc(), kaldi::ComputeNccf(), kaldi::nnet2::ComputeObjfAndGradient(), kaldi::ComputePowerSpectrum(), OnlinePreconditioner::ComputeWt1(), OnlineNaturalGradient::ComputeWt1(), OnlinePreconditioner::ComputeZt(), OnlineNaturalGradient::ComputeZt(), MatrixBase< float >::Cond(), LstmNonlinearityComponent::ConsolidateMemory(), kaldi::ConvolveSignals(), MatrixBase< float >::CopyColFromVec(), MatrixBase< float >::CopyColsFromVec(), CompressedMatrix::CopyColToVec(), MatrixBase< float >::CopyDiagFromVec(), SparseVector< Real >::CopyElementsToVec(), SparseMatrix< float >::CopyElementsToVec(), CuVectorBase< float >::CopyFromVec(), PackedMatrix< float >::CopyFromVec(), VectorBase< float >::CopyFromVec(), MatrixBase< float >::CopyRowFromVec(), MatrixBase< float >::CopyRowsFromVec(), CuMatrixBase< float >::CopyRowsFromVec(), CompressedMatrix::CopyRowToVec(), DiagGmmNormal::CopyToDiagGmm(), FullGmmNormal::CopyToFullGmm(), CuVectorBase< float >::CopyToVec(), kaldi::nnet1::CountCorrectFramesWeighted(), kaldi::cu::CpuBackpropLstmNonlinearity(), kaldi::CreateEigenvalueMatrix(), CuVector< float >::CuVector(), FmllrRawAccs::DataHasChanged(), FmllrDiagGmmAccs::DataHasChanged(), OnlineSpeexDecoder::Decode(), DeltaFeatures::DeltaFeatures(), MatrixBase< float >::DestructiveSvd(), kaldi::Dither(), VectorBase< float >::DivElements(), DecodableNnetSimple::DoNnetComputation(), kaldi::EBWUpdateGaussian(), SpMatrix< float >::Eig(), kaldi::ElementwiseProductOfFft(), OnlineSpeexEncoder::Encode(), SingleUtteranceGmmDecoder::EstimateFmllr(), FeatureTransformEstimate::EstimateInternal(), kaldi::EstimateSgmm2FmllrSubspace(), kaldi::EstPca(), Xent::Eval(), Mse::Eval(), kaldi::ExtendWaveWithSilence(), OnlinePitchFeatureImpl::ExtractFrame(), kaldi::ExtractObjectRange(), kaldi::ExtractWindow(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), kaldi::FindQuietestSegment(), kaldi::FrameLevelLpp(), AmSgmm2::GaussianSelection(), DiagGmm::Generate(), FullGmm::GetComponentMean(), DiagGmm::GetComponentMean(), DiagGmm::GetComponentVariance(), kaldi::GetFeatureMeanAndVariance(), OnlineIvectorFeature::GetFrame(), OnlineCmvn::GetFrame(), OnlineProcessPitch::GetFrame(), OnlineSpliceFrames::GetFrame(), OnlineDeltaFeature::GetFrame(), OnlinePitchFeatureImpl::GetFrame(), OnlineAppendFeature::GetFrame(), ParametricRelu::GetGradient(), LinearTransform::GetGradient(), AffineTransform::GetGradient(), RecurrentComponent::GetGradient(), ParallelComponent::GetGradient(), LstmProjected::GetGradient(), ConvolutionalComponent::GetGradient(), BlstmProjected::GetGradient(), AddShift::GetGradient(), Rescale::GetGradient(), EigenvalueDecomposition< Real >::GetImagEigenvalues(), OnlineIvectorEstimationStats::GetIvector(), IvectorExtractor::GetIvectorDistribution(), Nnet::GetLearningRates(), RegtreeFmllrDiagGmm::GetLogDets(), LogisticRegression::GetLogPosteriors(), kaldi::GetOccs(), ParametricRelu::GetParams(), LinearTransform::GetParams(), AffineTransform::GetParams(), RecurrentComponent::GetParams(), ParallelComponent::GetParams(), FramePoolingComponent::GetParams(), MultiBasisComponent::GetParams(), LstmProjected::GetParams(), ConvolutionalComponent::GetParams(), SentenceAveragingComponent::GetParams(), BlstmProjected::GetParams(), AddShift::GetParams(), Rescale::GetParams(), IvectorExtractor::GetPriorAuxf(), EigenvalueDecomposition< Real >::GetRealEigenvalues(), SingleUtteranceNnet2DecoderThreaded::GetRemainingWaveform(), kaldi::GetSplitTargets(), AmSgmm2::GetSubstateMean(), AmSgmm2::GetVarScaledSubstateSpeakerMean(), RestrictedAttentionComponent::Info(), FramePoolingComponent::InitData(), InitRand(), kaldi::InitRand(), FmllrRawAccs::InitSingleFrameStats(), OnlineGenericBaseFeature< C >::InputFinished(), kaldi::nnet3::KlDivergence(), kaldi::nnet2::KlDivergence(), MatrixBase< float >::LapackGesvd(), NnetDiscriminativeUpdater::LatticeComputations(), FullGmm::LogLikelihoods(), DiagGmm::LogLikelihoods(), FullGmm::LogLikelihoodsPreselect(), DiagGmm::LogLikelihoodsPreselect(), DecodableAmDiagGmmRegtreeFmllr::LogLikelihoodZeroBased(), DecodableAmDiagGmmUnmapped::LogLikelihoodZeroBased(), DecodableAmDiagGmmRegtreeMllr::LogLikelihoodZeroBased(), main(), TransitionModel::MapUpdate(), TransitionModel::MapUpdateShared(), DiagGmm::merged_components_logdet(), FullGmm::MergedComponentsLogdet(), kaldi::nnet3::MergeSupervision(), SoftmaxComponent::MixUp(), kaldi::MleDiagGmmUpdate(), TransitionModel::MleUpdate(), TransitionModel::MleUpdateShared(), kaldi::nnet1::MomentStatistics(), MatrixBase< float >::MulColsVec(), VectorBase< float >::MulElements(), MatrixBase< float >::MulRowsVec(), DiagGmmNormal::NumGauss(), FisherComputationClass::operator()(), CuVector< float >::operator=(), Vector< float >::operator=(), OptimizeLbfgs< Real >::OptimizeLbfgs(), PdfPrior::PdfPrior(), kaldi::Preemphasize(), TransitionModel::Print(), kaldi::nnet3::PrintPriorDiagnostics(), kaldi::nnet2::PrintPriorDiagnostics(), kaldi::nnet3::PrintVectorPerUpdatableComponent(), IvectorExtractorStats::PriorDiagnostics(), DeltaFeatures::Process(), ShiftedDeltaFeatures::Process(), kaldi::ProcessWindow(), kaldi::unittest::RandDiagGaussFeatures(), kaldi::unittest::RandFullGaussFeatures(), OnlineTcpVectorSource::Read(), OnlinePaSource::Read(), MleAmSgmm2Accs::Read(), OnlineVectorSource::Read(), VectorBase< float >::Read(), Vector< float >::Read(), PermuteComponent::Read(), kaldi::ReadData(), kaldi::RealFft(), kaldi::RealFftInefficient(), ArbitraryResample::Resample(), LinearResample::Resample(), DiagGmmNormal::Resize(), FullGmmNormal::Resize(), Sgmm2PerFrameDerivedVars::Resize(), Nnet::ScaleComponents(), DiagGmm::SetComponentInvVar(), DiagGmm::SetComponentMean(), ArbitraryResample::SetIndexes(), Nnet::SetLearningRates(), PitchFrameInfo::SetNccfPov(), Nnet::SetParams(), ParametricRelu::SetParams(), LinearTransform::SetParams(), AffineTransform::SetParams(), RecurrentComponent::SetParams(), ParallelComponent::SetParams(), ConvolutionalComponent::SetParams(), LstmProjected::SetParams(), BlstmProjected::SetParams(), AddShift::SetParams(), Rescale::SetParams(), kaldi::nnet2::SetPriors(), kaldi::nnet3::SetPriors(), AmNnetSimple::SetPriors(), LinearResample::SetRemainder(), Sgmm2PerSpkDerivedVars::SetSpeakerVector(), FullGmm::SetWeights(), DiagGmm::SetWeights(), kaldi::SolveQuadraticProblem(), kaldi::SortSvd(), SparseVector< Real >::SparseVector(), AmSgmm2::SplitSubstates(), NnetBatchComputer::SplitUtteranceIntoTasks(), RestrictedAttentionComponent::StoreStats(), SubVector< Real >::SubVector(), kaldi::nnet3::SummarizeVector(), MatrixBase< float >::SymPosSemiDefEig(), kaldi::nnet3::TestNnetDecodable(), SpMatrix< float >::TopEigs(), RegtreeFmllrDiagGmm::TransformFeature(), Plda::TransformIvector(), kaldi::TypeOneUsage(), kaldi::TypeThreeUsage(), kaldi::TypeTwoUsage(), kaldi::UnitTestCuMatrixSetRandUniform(), kaldi::UnitTestDelay(), UnitTestEstimateLda(), kaldi::UnitTestFFTbasedBlockConvolution(), kaldi::UnitTestFFTbasedConvolution(), UnitTestLinearResample(), UnitTestLinearResample2(), kaldi::UnitTestPieces(), kaldi::UnitTestPldaEstimation(), UnitTestReadWave(), kaldi::UnitTestReplaceValue(), kaldi::UnitTestSetRandUniform(), kaldi::UnitTestSimple(), UnitTestSimple(), kaldi::UnitTestSvdNodestroy(), ConvolutionComponent::UnVectorize(), TimeHeightConvolutionComponent::UnVectorize(), LstmNonlinearityComponent::UnVectorize(), AffineComponent::UnVectorize(), TdnnComponent::UnVectorize(), BlockAffineComponent::UnVectorize(), RepeatedAffineComponent::UnVectorize(), LinearComponent::UnVectorize(), CompositeComponent::UnVectorize(), kaldi::nnet3::UnVectorizeNnet(), MleSgmm2SpeakerAccs::Update(), kaldi::nnet3::UpdateNnetWithMaxChange(), MleSgmm2SpeakerAccs::UpdateNoU(), OnlinePitchFeatureImpl::UpdateRemainder(), EbwAmSgmm2Updater::UpdateSubstateWeights(), MleSgmm2SpeakerAccs::UpdateWithU(), kaldi::VecMatVec(), kaldi::VecSpVec(), kaldi::VecSvec(), Vector< float >::Vector(), ConvolutionComponent::Vectorize(), TimeHeightConvolutionComponent::Vectorize(), LstmNonlinearityComponent::Vectorize(), AffineComponent::Vectorize(), TdnnComponent::Vectorize(), BlockAffineComponent::Vectorize(), RepeatedAffineComponent::Vectorize(), LinearComponent::Vectorize(), CompositeComponent::Vectorize(), kaldi::nnet3::VectorizeNnet(), kaldi::VectorToPosteriorEntry(), kaldi::VecVec(), AccumDiagGmm::Write(), and kaldi::nnet3::WriteVectorAsChar().

64 { return dim_; }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397

◆ DivElements() [1/2]

void DivElements ( const VectorBase< Real > &  v)

Divide element-by-element by a vector.

Definition at line 1011 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), DiagGmm::GetComponentMean(), main(), and kaldi::SolveQuadraticProblem().

1011  {
1012  KALDI_ASSERT(dim_ == v.dim_);
1013  for (MatrixIndexT i = 0; i < dim_; i++) {
1014  data_[i] /= v.data_[i];
1015  }
1016 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ DivElements() [2/2]

void DivElements ( const VectorBase< OtherReal > &  v)

Divide element-by-element by a vector of different type.

Definition at line 1020 of file kaldi-vector.cc.

1020  {
1021  KALDI_ASSERT(dim_ == v.Dim());
1022  const OtherReal *other_ptr = v.Data();
1023  for (MatrixIndexT i = 0; i < dim_; i++) {
1024  data_[i] /= other_ptr[i];
1025  }
1026 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Floor()

void Floor ( const VectorBase< Real > &  v,
Real  floor_val,
MatrixIndexT floored_count = nullptr 
)

Applies floor to all elements.

Returns number of elements floored in floored_count if it is non-null.

Definition at line 812 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyFloor(), and VectorBase< float >::Range().

812  {
813  KALDI_ASSERT(dim_ == v.dim_);
814  if (floored_count == nullptr) {
815  for (MatrixIndexT i = 0; i < dim_; i++) {
816  data_[i] = std::max(v.data_[i], floor_val);
817  }
818  } else {
819  MatrixIndexT num_floored = 0;
820  for (MatrixIndexT i = 0; i < dim_; i++) {
821  if (v.data_[i] < floor_val) {
822  data_[i] = floor_val;
823  num_floored++;
824  } else {
825  data_[i] = v.data_[i];
826  }
827  }
828  *floored_count = num_floored;
829  }
830 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ InvertElements()

◆ IsZero()

bool IsZero ( Real  cutoff = 1.0e-06) const

Returns true if matrix is all zeros.

Definition at line 293 of file kaldi-vector.cc.

Referenced by MleAmSgmm2Accs::Check(), MleAmSgmm2Accs::CommitStatsForSpk(), main(), and kaldi::UnitTestSimpleForVec().

293  {
294  Real abs_max = 0.0;
295  for (MatrixIndexT i = 0; i < Dim(); i++)
296  abs_max = std::max(std::abs(data_[i]), abs_max);
297  return (abs_max <= cutoff);
298 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ KALDI_DISALLOW_COPY_AND_ASSIGN()

KALDI_DISALLOW_COPY_AND_ASSIGN ( VectorBase< Real >  )
protected

◆ LogSumExp()

Real LogSumExp ( Real  prune = -1.0) const

Returns log(sum(exp())) without exp overflow If prune > 0.0, ignores terms less than the max - prune.

[Note: in future, if prune = 0.0, it will take the max. For now, use -1 if you don't want it to prune.]

Definition at line 755 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), IvectorExtractor::GetAcousticAuxfWeight(), LogisticRegression::GetLogPosteriors(), FullGmm::LogLikelihood(), DiagGmm::LogLikelihood(), DecodableAmDiagGmmRegtreeMllr::LogLikelihoodZeroBased(), main(), kaldi::UnitTestDiagGmm(), UnitTestFullGmm(), MleAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleAmSgmm2Updater::UpdateW(), MleAmSgmm2Updater::UpdateWGetStats(), and MleSgmm2SpeakerAccs::UpdateWithU().

755  {
756  Real sum;
757  if (sizeof(sum) == 8) sum = kLogZeroDouble;
758  else sum = kLogZeroFloat;
759  Real max_elem = Max(), cutoff;
760  if (sizeof(Real) == 4) cutoff = max_elem + kMinLogDiffFloat;
761  else cutoff = max_elem + kMinLogDiffDouble;
762  if (prune > 0.0 && max_elem - prune > cutoff) // explicit pruning...
763  cutoff = max_elem - prune;
764 
765  double sum_relto_max_elem = 0.0;
766 
767  for (MatrixIndexT i = 0; i < dim_; i++) {
768  BaseFloat f = data_[i];
769  if (f >= cutoff)
770  sum_relto_max_elem += Exp(f - max_elem);
771  }
772  return max_elem + Log(sum_relto_max_elem);
773 }
double Exp(double x)
Definition: kaldi-math.h:83
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
static const double kMinLogDiffDouble
Definition: kaldi-math.h:124
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.
static const float kMinLogDiffFloat
Definition: kaldi-math.h:125
Real * data_
data memory area
Definition: kaldi-vector.h:395
const float kLogZeroFloat
Definition: kaldi-math.h:128
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ Max() [1/2]

Real Max ( ) const

Returns the maximum value of any element, or -infinity for the empty vector.

Definition at line 574 of file kaldi-vector.cc.

Referenced by kaldi::nnet3::ComputeAccuracy(), kaldi::ComputeEarlyReverbEnergy(), VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestMax(), OptimizeLbfgs< Real >::DoStep(), FeatureTransformEstimate::EstimateInternal(), kaldi::InitGmmFromRandomFrames(), SpMatrix< float >::LimitCond(), main(), CuVectorBase< float >::Max(), SpMatrix< float >::MaxAbsEig(), kaldi::MaxAbsolute(), kaldi::nnet1::MomentStatistics(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditioner::PreconditionDirectionsInternal(), OnlineNaturalGradient::PreconditionDirectionsInternal(), kaldi::nnet2::PrintPriorDiagnostics(), kaldi::nnet3::PrintPriorDiagnostics(), kaldi::SolveQuadraticMatrixProblem(), kaldi::SolveQuadraticProblem(), SpMatrix< float >::SymPosSemiDefEig(), kaldi::TestVectorToPosteriorEntry(), kaldi::UnitTestMaxAbsEig(), kaldi::UnitTestMaxMin(), kaldi::UnitTestSparseVectorMax(), kaldi::UnitTestVectorMax(), IvectorExtractorStats::UpdatePrior(), and kaldi::VectorToPosteriorEntry().

574  {
575  Real ans = - std::numeric_limits<Real>::infinity();
576  const Real *data = data_;
577  MatrixIndexT i, dim = dim_;
578  for (i = 0; i + 4 <= dim; i += 4) {
579  Real a1 = data[i], a2 = data[i+1], a3 = data[i+2], a4 = data[i+3];
580  if (a1 > ans || a2 > ans || a3 > ans || a4 > ans) {
581  Real b1 = (a1 > a2 ? a1 : a2), b2 = (a3 > a4 ? a3 : a4);
582  if (b1 > ans) ans = b1;
583  if (b2 > ans) ans = b2;
584  }
585  }
586  for (; i < dim; i++)
587  if (data[i] > ans) ans = data[i];
588  return ans;
589 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Max() [2/2]

Real Max ( MatrixIndexT index) const

Returns the maximum value of any element, and the associated index.

Error if vector is empty.

Definition at line 592 of file kaldi-vector.cc.

592  {
593  if (dim_ == 0) KALDI_ERR << "Empty vector";
594  Real ans = - std::numeric_limits<Real>::infinity();
595  MatrixIndexT index = 0;
596  const Real *data = data_;
597  MatrixIndexT i, dim = dim_;
598  for (i = 0; i + 4 <= dim; i += 4) {
599  Real a1 = data[i], a2 = data[i+1], a3 = data[i+2], a4 = data[i+3];
600  if (a1 > ans || a2 > ans || a3 > ans || a4 > ans) {
601  if (a1 > ans) { ans = a1; index = i; }
602  if (a2 > ans) { ans = a2; index = i + 1; }
603  if (a3 > ans) { ans = a3; index = i + 2; }
604  if (a4 > ans) { ans = a4; index = i + 3; }
605  }
606  }
607  for (; i < dim; i++)
608  if (data[i] > ans) { ans = data[i]; index = i; }
609  *index_out = index;
610  return ans;
611 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Min() [1/2]

Real Min ( ) const

Returns the minimum value of any element, or +infinity for the empty vector.

Definition at line 614 of file kaldi-vector.cc.

Referenced by kaldi::ApplyHessianXformToGradient(), kaldi::ApplyInvHessianXformToChange(), Plda::ApplyTransform(), VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestMin(), OptimizeLbfgs< Real >::DoStep(), kaldi::EBWUpdateGaussian(), kaldi::GetFeatureMeanAndVariance(), PldaEstimator::GetOutput(), main(), SpMatrix< float >::MaxAbsEig(), kaldi::MaxAbsolute(), CuVectorBase< float >::Min(), MatrixBase< float >::MinSingularValue(), kaldi::nnet1::MomentStatistics(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), Nnet::SetLearningRates(), SpMatrix< float >::SymPosSemiDefEig(), kaldi::UnitTestFloorUnit(), kaldi::UnitTestMaxAbsEig(), kaldi::UnitTestMaxMin(), kaldi::UnitTestVectorMin(), and IvectorExtractorStats::UpdatePrior().

614  {
615  Real ans = std::numeric_limits<Real>::infinity();
616  const Real *data = data_;
617  MatrixIndexT i, dim = dim_;
618  for (i = 0; i + 4 <= dim; i += 4) {
619  Real a1 = data[i], a2 = data[i+1], a3 = data[i+2], a4 = data[i+3];
620  if (a1 < ans || a2 < ans || a3 < ans || a4 < ans) {
621  Real b1 = (a1 < a2 ? a1 : a2), b2 = (a3 < a4 ? a3 : a4);
622  if (b1 < ans) ans = b1;
623  if (b2 < ans) ans = b2;
624  }
625  }
626  for (; i < dim; i++)
627  if (data[i] < ans) ans = data[i];
628  return ans;
629 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Min() [2/2]

Real Min ( MatrixIndexT index) const

Returns the minimum value of any element, and the associated index.

Error if vector is empty.

Definition at line 632 of file kaldi-vector.cc.

632  {
633  if (dim_ == 0) KALDI_ERR << "Empty vector";
634  Real ans = std::numeric_limits<Real>::infinity();
635  MatrixIndexT index = 0;
636  const Real *data = data_;
637  MatrixIndexT i, dim = dim_;
638  for (i = 0; i + 4 <= dim; i += 4) {
639  Real a1 = data[i], a2 = data[i+1], a3 = data[i+2], a4 = data[i+3];
640  if (a1 < ans || a2 < ans || a3 < ans || a4 < ans) {
641  if (a1 < ans) { ans = a1; index = i; }
642  if (a2 < ans) { ans = a2; index = i + 1; }
643  if (a3 < ans) { ans = a3; index = i + 2; }
644  if (a4 < ans) { ans = a4; index = i + 3; }
645  }
646  }
647  for (; i < dim; i++)
648  if (data[i] < ans) { ans = data[i]; index = i; }
649  *index_out = index;
650  return ans;
651 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ MulElements() [1/2]

void MulElements ( const VectorBase< Real > &  v)

◆ MulElements() [2/2]

void MulElements ( const VectorBase< OtherReal > &  v)

Multiply element-by-element by another vector of different type.

Definition at line 985 of file kaldi-vector.cc.

985  {
986  KALDI_ASSERT(dim_ == v.Dim());
987  const OtherReal *other_ptr = v.Data();
988  for (MatrixIndexT i = 0; i < dim_; i++) {
989  data_[i] *= other_ptr[i];
990  }
991 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MulTp()

void MulTp ( const TpMatrix< Real > &  M,
const MatrixTransposeType  trans 
)

Multiplies this vector by lower-triangular matrix: *this <– *this *M.

Definition at line 152 of file kaldi-vector.cc.

Referenced by VectorBase< float >::AddTpVec(), VectorBase< float >::ApplyPow(), FullGmm::Perturb(), FullGmm::Split(), kaldi::UnitTestCuVectorMulTp(), and kaldi::UnitTestMulTp().

153  {
154  KALDI_ASSERT(M.NumRows() == dim_);
155  cblas_Xtpmv(trans,M.Data(),M.NumRows(),data_,1);
156 }
void cblas_Xtpmv(MatrixTransposeType trans, const float *Mdata, const int num_rows, float *y, const int y_inc)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Norm()

Real Norm ( Real  p) const

Compute the p-th norm of the vector.

Definition at line 512 of file kaldi-vector.cc.

Referenced by OptimizeLbfgs< Real >::AcceptStep(), VectorBase< float >::ApplyPow(), VectorBase< float >::ApproxEqual(), OptimizeLbfgs< Real >::ComputeHifNeeded(), IvectorExtractor::GetIvectorDistribution(), PldaEstimator::GetOutput(), main(), VectorBase< float >::Norm(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlineIvectorFeature::PrintDiagnostics(), OptimizeLbfgs< Real >::Restart(), Plda::TransformIvector(), kaldi::UnitTestLbfgs(), kaldi::UnitTestLinearCgd(), kaldi::UnitTestNorm(), kaldi::UnitTestSimpleForVec(), IvectorExtractorStats::UpdatePrior(), and IvectorExtractTask::~IvectorExtractTask().

512  {
513  KALDI_ASSERT(p >= 0.0);
514  Real sum = 0.0;
515  if (p == 0.0) {
516  for (MatrixIndexT i = 0; i < dim_; i++)
517  if (data_[i] != 0.0) sum += 1.0;
518  return sum;
519  } else if (p == 1.0) {
520  for (MatrixIndexT i = 0; i < dim_; i++)
521  sum += std::abs(data_[i]);
522  return sum;
523  } else if (p == 2.0) {
524  for (MatrixIndexT i = 0; i < dim_; i++)
525  sum += data_[i] * data_[i];
526  return std::sqrt(sum);
527  } else if (p == std::numeric_limits<Real>::infinity()){
528  for (MatrixIndexT i = 0; i < dim_; i++)
529  sum = std::max(sum, std::abs(data_[i]));
530  return sum;
531  } else {
532  Real tmp;
533  bool ok = true;
534  for (MatrixIndexT i = 0; i < dim_; i++) {
535  tmp = pow(std::abs(data_[i]), p);
536  if (tmp == HUGE_VAL) // HUGE_VAL is what pow returns on error.
537  ok = false;
538  sum += tmp;
539  }
540  tmp = pow(sum, static_cast<Real>(1.0/p));
541  KALDI_ASSERT(tmp != HUGE_VAL); // should not happen here.
542  if (ok) {
543  return tmp;
544  } else {
545  Real maximum = this->Max(), minimum = this->Min(),
546  max_abs = std::max(maximum, -minimum);
547  KALDI_ASSERT(max_abs > 0); // Or should not have reached here.
548  Vector<Real> tmp(*this);
549  tmp.Scale(1.0 / max_abs);
550  return tmp.Norm(p) * max_abs;
551  }
552  }
553 }
Real Min() const
Returns the minimum value of any element, or +infinity for the empty vector.
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ operator()() [1/2]

Real operator() ( MatrixIndexT  i) const
inline

Indexing operator (const).

Definition at line 76 of file kaldi-vector.h.

76  {
77  KALDI_PARANOID_ASSERT(static_cast<UnsignedMatrixIndexT>(i) <
78  static_cast<UnsignedMatrixIndexT>(dim_));
79  return *(data_ + i);
80  }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_PARANOID_ASSERT(cond)
Definition: kaldi-error.h:206
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ operator()() [2/2]

Real& operator() ( MatrixIndexT  i)
inline

Indexing operator (non-const).

Definition at line 83 of file kaldi-vector.h.

83  {
84  KALDI_PARANOID_ASSERT(static_cast<UnsignedMatrixIndexT>(i) <
85  static_cast<UnsignedMatrixIndexT>(dim_));
86  return *(data_ + i);
87  }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
#define KALDI_PARANOID_ASSERT(cond)
Definition: kaldi-error.h:206
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Pow()

void Pow ( const VectorBase< Real > &  v,
Real  power 
)

Definition at line 468 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and VectorBase< float >::Range().

468  {
469  KALDI_ASSERT(dim_ == v.dim_);
470  for (MatrixIndexT i = 0; i < dim_; i++) {
471  data_[i] = pow(v.data_[i], power);
472  }
473 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandCategorical()

MatrixIndexT RandCategorical ( ) const

This function returns a random index into this vector, chosen with probability proportional to the corresponding element.

Requires that this->Min() >= 0 and this->Sum() > 0.

Definition at line 319 of file kaldi-vector.cc.

Referenced by FullGmmNormal::Rand(), and kaldi::UnitTestRandCategorical().

319  {
320  kaldi::RandomState rstate;
321  Real sum = this->Sum();
322  KALDI_ASSERT(this->Min() >= 0.0 && sum > 0.0);
323  Real r = RandUniform(&rstate) * sum;
324  Real *data = this->data_;
325  MatrixIndexT dim = this->dim_;
326  Real running_sum = 0.0;
327  for (MatrixIndexT i = 0; i < dim; i++) {
328  running_sum += data[i];
329  if (r < running_sum) return i;
330  }
331  return dim_ - 1; // Should only happen if RandUniform()
332  // returns exactly 1, or due to roundoff.
333 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
Real Min() const
Returns the minimum value of any element, or +infinity for the empty vector.
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real Sum() const
Returns sum of the elements.
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Range() [1/2]

SubVector<Real> Range ( const MatrixIndexT  o,
const MatrixIndexT  l 
)
inline

Returns a sub-vector of a vector (a range of elements).

Parameters
o[in] Origin, 0 < o < Dim()
l[in] Length 0 < l < Dim()-o
Returns
A SubVector object that aliases the data of the Vector object. See SubVector class for details

Definition at line 94 of file kaldi-vector.h.

Referenced by OnlineSpeexEncoder::AcceptWaveform(), OnlineGenericBaseFeature< C >::AcceptWaveform(), RegtreeFmllrDiagGmmAccs::AccumulateForGaussian(), RegtreeFmllrDiagGmmAccs::AccumulateForGmm(), FmllrSgmm2Accs::AccumulateFromPosteriors(), kaldi::AddVectorsOfUnequalLength(), kaldi::AddVectorsWithOffset(), kaldi::AppendVector(), Fmpe::ApplyProjection(), Fmpe::ApplyProjectionReverse(), FmllrRawAccs::CommitSingleFrameStats(), FmllrDiagGmmAccs::CommitSingleFrameStats(), MelBanks::Compute(), PlpComputer::Compute(), OnlineFeInput< E >::Compute(), BasisFmllrEstimate::ComputeAmDiagPrecond(), kaldi::ComputeEarlyReverbEnergy(), Sgmm2Project::ComputeLdaTransform(), kaldi::ExtendWaveWithSilence(), OnlinePitchFeatureImpl::ExtractFrame(), kaldi::ExtractObjectRange(), CompressedAffineXformStats::ExtractOneG(), kaldi::ExtractWindow(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), kaldi::FindQuietestSegment(), FmllrDiagGmmAccs::FmllrDiagGmmAccs(), kaldi::FmllrInnerUpdate(), ParametricRelu::GetGradient(), Nnet::GetGradient(), AffineTransform::GetGradient(), RecurrentComponent::GetGradient(), ParallelComponent::GetGradient(), LstmProjected::GetGradient(), ConvolutionalComponent::GetGradient(), BlstmProjected::GetGradient(), IvectorExtractor::GetIvectorDistribution(), Nnet::GetParams(), ParametricRelu::GetParams(), AffineTransform::GetParams(), RecurrentComponent::GetParams(), ParallelComponent::GetParams(), FramePoolingComponent::GetParams(), MultiBasisComponent::GetParams(), LstmProjected::GetParams(), ConvolutionalComponent::GetParams(), BlstmProjected::GetParams(), SingleUtteranceNnet2DecoderThreaded::GetRemainingWaveform(), FramePoolingComponent::InitData(), OnlineSpeexEncoder::InputFinished(), OnlineGenericBaseFeature< C >::InputFinished(), main(), MelBanks::MelBanks(), kaldi::MergeFullGmm(), SoftmaxComponent::MixUp(), kaldi::RealFftInefficient(), Nnet::SetParams(), ParametricRelu::SetParams(), AffineTransform::SetParams(), RecurrentComponent::SetParams(), ParallelComponent::SetParams(), MultiBasisComponent::SetParams(), ConvolutionalComponent::SetParams(), LstmProjected::SetParams(), BlstmProjected::SetParams(), SpMatrix< float >::TopEigs(), kaldi::UnitTestCuVectorSum(), UnitTestLinearResample(), kaldi::UnitTestRange(), UnitTestVectorRandomizer(), ConvolutionComponent::UnVectorize(), TimeHeightConvolutionComponent::UnVectorize(), Nnet::UnVectorize(), TdnnComponent::UnVectorize(), RepeatedAffineComponent::UnVectorize(), AffineComponent::UnVectorize(), BlockAffineComponent::UnVectorize(), ScaleAndOffsetComponent::UnVectorize(), ConvolutionComponent::Vectorize(), TimeHeightConvolutionComponent::Vectorize(), TdnnComponent::Vectorize(), RepeatedAffineComponent::Vectorize(), AffineComponent::Vectorize(), BlockAffineComponent::Vectorize(), and ScaleAndOffsetComponent::Vectorize().

94  {
95  return SubVector<Real>(*this, o, l);
96  }

◆ Range() [2/2]

const SubVector<Real> Range ( const MatrixIndexT  o,
const MatrixIndexT  l 
) const
inline

Returns a const sub-vector of a vector (a range of elements).

Parameters
o[in] Origin, 0 < o < Dim()
l[in] Length 0 < l < Dim()-o
Returns
A SubVector object that aliases the data of the Vector object. See SubVector class for details

Definition at line 103 of file kaldi-vector.h.

104  {
105  return SubVector<Real>(*this, o, l);
106  }

◆ Read()

void Read ( std::istream &  in,
bool  binary,
bool  add = false 
)

Reads from C++ stream (option to add to existing contents).

Throws exception on failure

Definition at line 1086 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), kaldi::operator>>(), and Vector< float >::~Vector().

1086  {
1087  if (add) {
1088  Vector<Real> tmp(Dim());
1089  tmp.Read(is, binary, false); // read without adding.
1090  if (this->Dim() != tmp.Dim()) {
1091  KALDI_ERR << "VectorBase::Read, size mismatch " << this->Dim()<<" vs. "<<tmp.Dim();
1092  }
1093  this->AddVec(1.0, tmp);
1094  return;
1095  } // now assume add == false.
1096 
1097  // In order to avoid rewriting this, we just declare a Vector and
1098  // use it to read the data, then copy.
1099  Vector<Real> tmp;
1100  tmp.Read(is, binary, false);
1101  if (tmp.Dim() != Dim())
1102  KALDI_ERR << "VectorBase<Real>::Read, size mismatch "
1103  << Dim() << " vs. " << tmp.Dim();
1104  CopyFromVec(tmp);
1105 }
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
#define KALDI_ERR
Definition: kaldi-error.h:147
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...

◆ ReplaceValue()

void ReplaceValue ( Real  orig,
Real  changed 
)

Set each element to y = (x == orig ? changed : x).

Definition at line 976 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), kaldi::UnitTestCuVectorReplaceValue(), and kaldi::UnitTestReplaceValue().

976  {
977  Real *data = data_;
978  for (MatrixIndexT i = 0; i < dim_; i++)
979  if (data[i] == orig) data[i] = changed;
980 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Scale()

void Scale ( Real  alpha)

Multiplies all elements by this constant.

Definition at line 963 of file kaldi-vector.cc.

Referenced by FmllrSgmm2Accs::AccumulateForFmllrSubspace(), FmllrDiagGmmAccs::AccumulateForGmm(), FmllrRawAccs::AccumulateForGmm(), RegtreeMllrDiagGmmAccs::AccumulateForGmm(), RegtreeFmllrDiagGmmAccs::AccumulateForGmm(), AccumAmDiagGmm::AccumulateForGmmTwofeats(), kaldi::AddNoise(), kaldi::AlignUtteranceWrapper(), VectorBase< float >::ApplyPow(), RegressionTree::BuildTree(), kaldi::ClusterGaussiansToUbm(), PlpComputer::Compute(), kaldi::ComputeAmGmmFeatureDeriv(), Fmpe::ComputeC(), kaldi::ComputeFeatureNormalizingTransform(), AmSgmm2::ComputeFmllrPreXform(), EbwAmSgmm2Updater::ComputePhoneVecStats(), LstmNonlinearityComponent::ConsolidateMemory(), FmllrRawAccs::ConvertToSimpleStats(), kaldi::CuVectorUnitTestScale(), DeltaFeatures::DeltaFeatures(), MatrixBase< float >::DestructiveSvd(), kaldi::EBWUpdateGaussian(), BasisFmllrEstimate::EstimateFmllrBasis(), kaldi::EstPca(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), kaldi::FmllrInnerUpdate(), kaldi::GenRandStats(), IvectorExtractor::GetAcousticAuxfVariance(), kaldi::GetFeatDeriv(), kaldi::GetFeatureMeanAndVariance(), SingleUtteranceGmmDecoder::GetGaussianPosteriors(), PldaEstimator::GetOutput(), LdaEstimate::GetStats(), BatchNormComponent::Info(), LstmNonlinearityComponent::Info(), NonlinearComponent::Info(), ConstantComponent::InitFromConfig(), ConstantFunctionComponent::InitFromConfig(), kaldi::unittest::InitRandDiagGmm(), kaldi::unittest::InitRandFullGmm(), kaldi::InitRandomGmm(), kaldi::IsmoothStatsDiagGmm(), main(), kaldi::MapDiagGmmUpdate(), FullGmm::Merge(), DiagGmm::merged_components_logdet(), FullGmm::MergedComponentsLogdet(), DiagGmm::MergeKmeans(), kaldi::MleDiagGmmUpdate(), kaldi::MleFullGmmUpdate(), TransitionModel::MleUpdate(), TransitionModel::MleUpdateShared(), VectorBase< float >::Norm(), PdfPrior::PdfPrior(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditioner::PreconditionDirectionsInternal(), OnlineNaturalGradient::PreconditionDirectionsInternal(), DiscriminativeObjectiveInfo::Print(), IvectorExtractorStats::PriorDiagnostics(), rand_diag_gmm(), kaldi::RealFft(), LdaEstimate::Scale(), AccumFullGmm::Scale(), AccumDiagGmm::Scale(), RestrictedAttentionComponent::Scale(), kaldi::SlidingWindowCmnInternal(), AccumDiagGmm::SmoothStats(), kaldi::TestClusterKMeansVector(), kaldi::nnet3::TestNnetComponentUpdatable(), kaldi::TestVectorToPosteriorEntry(), SpMatrix< float >::TopEigs(), Plda::TransformIvector(), kaldi::UnitTestAddDiagMat2(), kaldi::UnitTestAddDiagMatMat(), kaldi::UnitTestAddDiagVecMat(), kaldi::nnet2::UnitTestAmNnet(), kaldi::UnitTestComplexFft(), kaldi::UnitTestComplexFt(), kaldi::UnitTestCuVectorAddColSumMat(), kaldi::UnitTestCuVectorAddColSumMatLarge(), kaldi::UnitTestCuVectorAddRowSumMat(), kaldi::UnitTestCuVectorAddRowSumMatLarge(), kaldi::UnitTestCuVectorAddVec(), UnitTestEstimateDiagGmm(), UnitTestEstimateFullGmm(), UnitTestEstimateLda(), kaldi::UnitTestEstimateMmieDiagGmm(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), kaldi::UnitTestLbfgs(), kaldi::nnet2::UnitTestNnetDecodable(), kaldi::UnitTestNorm(), kaldi::UnitTestPldaEstimation(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), kaldi::UnitTestRealFft(), kaldi::UnitTestSimpleForVec(), kaldi::UnitTestSplitRadixComplexFft(), kaldi::UnitTestSplitRadixRealFft(), kaldi::UnitTestVector(), kaldi::nnet3::UpdateNnetWithMaxChange(), IvectorExtractorStats::UpdatePrior(), EbwAmSgmm2Updater::UpdateSubstateWeights(), EbwAmSgmm2Updater::UpdateU(), MleAmSgmm2Updater::UpdateU(), MleAmSgmm2Updater::UpdateW(), MleSgmm2SpeakerAccs::UpdateWithU(), VectorClusterable::VectorClusterable(), LstmNonlinearityComponent::Write(), and NonlinearComponent::Write().

963  {
964  cblas_Xscal(dim_, alpha, data_, 1);
965 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
void cblas_Xscal(const int N, const float alpha, float *data, const int inc)
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Set()

void Set ( Real  f)

Set all members of a vector to a specified value.

Definition at line 336 of file kaldi-vector.cc.

Referenced by VectorBase< float >::AddColSumMat(), VectorBase< float >::AddRowSumMat(), MatrixBase< float >::AddVecToCols(), MatrixBase< float >::AddVecToRows(), kaldi::nnet2::CombineNnetsA(), kaldi::nnet3::ComputeAccuracy(), kaldi::ComputeLocalCost(), kaldi::nnet2::GetInitialModel(), FastNnetCombiner::GetInitialModel(), FastNnetCombiner::GetInitialParams(), kaldi::nnet2::GetInitialScaleParams(), LogisticRegression::GetLogPosteriors(), kaldi::nnet2::GetUpdateDirection(), OnlinePreconditionerSimple::InitDefault(), OnlineNaturalGradientSimple::InitDefault(), main(), kaldi::ReadData(), kaldi::SlidingWindowCmnInternal(), Plda::SmoothWithinClassCovariance(), kaldi::TestRecyclingVector(), TestSgmm2FmllrAccsIO(), TestSgmm2FmllrSubspace(), TestSgmm2PreXform(), kaldi::TrainOneIter(), kaldi::UnitTestAddVecToCols(), kaldi::UnitTestAddVecToRows(), UnitTestRegressionTree(), kaldi::UnitTestSimpleForVec(), and kaldi::nnet3::time_height_convolution::ZeroBlankRows().

336  {
337  // Why not use memset here?
338  // The basic unit of memset is a byte.
339  // If f != 0 and sizeof(Real) > 1, then we cannot use memset.
340  if (f == 0) {
341  this->SetZero(); // calls std::memset
342  } else {
343  for (MatrixIndexT i = 0; i < dim_; i++) { data_[i] = f; }
344  }
345 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
void SetZero()
Set vector to all zeros.

◆ SetRandn()

void SetRandn ( )

Set vector to random normally-distributed noise.

Definition at line 301 of file kaldi-vector.cc.

Referenced by kaldi::CuVectorUnitTestAddVecVec(), ConstantComponent::InitFromConfig(), ConstantFunctionComponent::InitFromConfig(), main(), LogisticRegression::MixUp(), SoftmaxComponent::MixUp(), PitchInterpolator::MultiplyObsProb(), FullGmm::Perturb(), FullGmmNormal::Rand(), FullGmm::Split(), kaldi::TestClusterKMeansVector(), kaldi::TestClusterUtilsVector(), kaldi::nnet3::TestNnetDecodable(), kaldi::TestVectorToPosteriorEntry(), SpMatrix< float >::TopEigs(), kaldi::UnitTestAddDiagMat2(), kaldi::UnitTestAddDiagMatMat(), kaldi::UnitTestAddDiagVecMat(), kaldi::UnitTestAddMatDiagVec(), kaldi::UnitTestAddOuterProductPlusMinus(), kaldi::UnitTestAddVec2Sp(), kaldi::UnitTestAddVecCross(), kaldi::UnitTestAddVecToCols(), kaldi::UnitTestAddVecToColsSpeed(), kaldi::UnitTestAddVecToRows(), kaldi::UnitTestAddVecToRowsSpeed(), kaldi::UnitTestAddVecVec(), kaldi::nnet2::UnitTestAmNnet(), kaldi::UnitTestBackpropLstmNonlinearity(), kaldi::UnitTestCopyRowsAndCols(), kaldi::UnitTestCuMatrixAddVecVec(), kaldi::UnitTestCuSpMatrixAddVec2(), kaldi::UnitTestCuVectorAddTp(), kaldi::UnitTestCuVectorCopyFromVec(), kaldi::UnitTestCuVectorMulTp(), kaldi::UnitTestCuVectorReplaceValue(), kaldi::UnitTestDotprod(), kaldi::UnitTestFFTbasedBlockConvolution(), kaldi::UnitTestFFTbasedConvolution(), kaldi::UnitTestFloorCeiling(), kaldi::UnitTestFloorChol(), kaldi::UnitTestInnerProd(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), kaldi::UnitTestLbfgs(), kaldi::UnitTestLinearCgd(), UnitTestLinearResample(), UnitTestLinearResample2(), kaldi::UnitTestMaxMin(), kaldi::UnitTestMul(), kaldi::UnitTestMulTp(), kaldi::nnet2::UnitTestNnetDecodable(), kaldi::UnitTestNorm(), kaldi::UnitTestPldaEstimation(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), kaldi::UnitTestRange(), kaldi::UnitTestRemoveRow(), kaldi::UnitTestReplaceValue(), kaldi::UnitTestResize(), kaldi::UnitTestScale(), kaldi::UnitTestSger(), kaldi::UnitTestSimpleForMat(), kaldi::UnitTestSolve(), kaldi::UnitTestSpAddDiagVec(), kaldi::UnitTestSpAddVecVec(), kaldi::UnitTestSparseVectorAddToVec(), kaldi::UnitTestSparseVectorMax(), kaldi::UnitTestSparseVectorSum(), kaldi::UnitTestSparseVectorVecSvec(), kaldi::UnitTestSubvector(), kaldi::nnet3::UnitTestSummarizeVector(), kaldi::UnitTestTriVecSolver(), kaldi::UnitTestVecmul(), kaldi::UnitTestVector(), kaldi::UnitTestVectorMax(), and kaldi::UnitTestVectorMin().

301  {
302  kaldi::RandomState rstate;
303  MatrixIndexT last = (Dim() % 2 == 1) ? Dim() - 1 : Dim();
304  for (MatrixIndexT i = 0; i < last; i += 2) {
305  kaldi::RandGauss2(data_ + i, data_ + i + 1, &rstate);
306  }
307  if (Dim() != last) data_[last] = static_cast<Real>(kaldi::RandGauss(&rstate));
308 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
void RandGauss2(float *a, float *b, RandomState *state)
Definition: kaldi-math.cc:139
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ SetRandUniform()

void SetRandUniform ( )

Sets to numbers uniformly distributed on (0,1)

Definition at line 311 of file kaldi-vector.cc.

311  {
312  kaldi::RandomState rstate;
313  for (MatrixIndexT i = 0; i < Dim(); i++) {
314  *(data_+i) = RandUniform(&rstate);
315  }
316 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ SetZero()

◆ Sigmoid()

void Sigmoid ( const VectorBase< Real > &  src)

Sets each element of *this to the sigmoid function of the corresponding element of "src".

Definition at line 938 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyCeiling(), and MatrixBase< float >::Sigmoid().

938  {
939  KALDI_ASSERT(dim_ == src.dim_);
940  for (MatrixIndexT i = 0; i < dim_; i++) {
941  Real x = src.data_[i];
942  // We aim to avoid floating-point overflow here.
943  if (x > 0.0) {
944  x = 1.0 / (1.0 + Exp(-x));
945  } else {
946  Real ex = Exp(x);
947  x = ex / (ex + 1.0);
948  }
949  data_[i] = x;
950  }
951 }
double Exp(double x)
Definition: kaldi-math.h:83
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SizeInBytes()

MatrixIndexT SizeInBytes ( ) const
inline

Returns the size in memory of the vector, in bytes.

Definition at line 67 of file kaldi-vector.h.

67 { return (dim_*sizeof(Real)); }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397

◆ Solve()

void Solve ( const TpMatrix< Real > &  M,
const MatrixTransposeType  trans 
)

If trans == kNoTrans, solves M x = b, where b is the value of *this at input and x is the value of *this at output.

If trans == kTrans, solves M' x = b. Does not test for M being singular or near-singular, so test it before calling this routine.

Definition at line 159 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyPow(), and kaldi::UnitTestTriVecSolver().

160  {
161  KALDI_ASSERT(M.NumRows() == dim_);
162  cblas_Xtpsv(trans, M.Data(), M.NumRows(), data_, 1);
163 }
void cblas_Xtpsv(MatrixTransposeType trans, const float *Mdata, const int num_rows, float *y, const int y_inc)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Sum()

Real Sum ( ) const

Returns sum of the elements.

Definition at line 688 of file kaldi-vector.cc.

Referenced by OnlinePitchFeatureImpl::AcceptWaveform(), AccumAmDiagGmm::AccumulateFromPosteriors(), FmllrDiagGmmAccs::AccumulateFromPosteriors(), FmllrDiagGmmAccs::AccumulateFromPosteriorsPreselect(), Nnet::Check(), kaldi::ClusterGaussiansToUbm(), IvectorExtractorStats::CommitStatsForWPoint(), kaldi::nnet3::ComputeAccuracy(), kaldi::ComputeCorrelation(), AmSgmm2::ComputeFmllrPreXform(), EbwAmSgmm2Updater::ComputePhoneVecStats(), kaldi::ComputeVadEnergy(), OnlinePreconditioner::ComputeWt1(), OnlineNaturalGradient::ComputeWt1(), VectorBase< float >::CopyDiagFromTp(), kaldi::CuVectorUnitTestCopyDiagFromMat(), kaldi::CuVectorUnitTestSum(), kaldi::EstPca(), Xent::Eval(), Mse::Eval(), kaldi::GenRandStats(), IvectorExtractor::GetAcousticAuxf(), IvectorExtractor::GetAcousticAuxfVariance(), IvectorExtractor::GetAuxf(), IvectorExtractor::GetIvectorDistWeight(), LdaEstimate::GetStats(), kaldi::unittest::InitRandDiagGmm(), kaldi::InitRandomGmm(), IvectorExtractorStats::IvectorVarianceDiagnostic(), kaldi::nnet3::KlDivergence(), kaldi::nnet2::KlDivergence(), AffineComponent::LimitRank(), main(), TransitionModel::MapUpdate(), TransitionModel::MapUpdateShared(), kaldi::MleFullGmmUpdate(), TransitionModel::MleUpdate(), TransitionModel::MleUpdateShared(), kaldi::nnet1::MomentStatistics(), LimitRankClass::operator()(), PdfPrior::PdfPrior(), BackpropTruncationComponent::PrecomputeIndexes(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditioner::PreconditionDirectionsInternal(), OnlineNaturalGradient::PreconditionDirectionsInternal(), IvectorExtractorStats::PriorDiagnostics(), kaldi::ProcessWindow(), MleAmSgmm2Updater::RenormalizeN(), MleAmSgmm2Updater::RenormalizeV(), OnlineNaturalGradient::ReorthogonalizeRt1(), OnlinePreconditioner::ReorthogonalizeXt1(), Xent::Report(), CuVectorBase< float >::Sum(), kaldi::nnet3::SummarizeVector(), kaldi::TestCuVectorCopyFromVec(), kaldi::TraceMatMat(), kaldi::nnet2::UnitTestAmNnet(), kaldi::UnitTestDiagGmm(), kaldi::UnitTestEigSymmetric(), UnitTestFullGmm(), kaldi::nnet2::UnitTestNnetDecodable(), kaldi::UnitTestPosteriors(), kaldi::UnitTestRandCategorical(), kaldi::UnitTestRange(), kaldi::UnitTestResize(), kaldi::UnitTestSimpleForVec(), kaldi::UnitTestSparseVectorSum(), MleSgmm2SpeakerAccs::Update(), IvectorExtractorStats::Update(), kaldi::UpdateEbwWeightsDiagGmm(), EbwAmSgmm2Updater::UpdateM(), EbwAmSgmm2Updater::UpdateN(), MleSgmm2SpeakerAccs::UpdateNoU(), IvectorExtractorStats::UpdateProjections(), OnlinePitchFeatureImpl::UpdateRemainder(), EbwAmSgmm2Updater::UpdateSubstateWeights(), MleAmSgmm2Updater::UpdateSubstateWeights(), EbwAmSgmm2Updater::UpdateU(), MleAmSgmm2Updater::UpdateU(), IvectorExtractorStats::UpdateVariances(), MleAmSgmm2Updater::UpdateVars(), EbwAmSgmm2Updater::UpdateW(), MleAmSgmm2Updater::UpdateW(), IvectorExtractorStats::UpdateWeights(), MleSgmm2SpeakerAccs::UpdateWithU(), and MleAmSgmm2Accs::~MleAmSgmm2Accs().

688  {
689  // Do a dot-product with a size-1 array with a stride of 0 to
690  // implement sum. This allows us to access SIMD operations in a
691  // cross-platform way via your BLAS library.
692  Real one(1);
693  return cblas_Xdot(dim_, data_, 1, &one, 0);
694 }
float cblas_Xdot(const int N, const float *const X, const int incX, const float *const Y, const int incY)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ SumLog()

Real SumLog ( ) const

Returns sum of the logs of the elements.

More efficient than just taking log of each. Will return NaN if any elements are negative.

Definition at line 697 of file kaldi-vector.cc.

Referenced by VectorBase< float >::CopyDiagFromTp(), Plda::LogLikelihoodRatio(), main(), and GaussClusterable::Objf().

697  {
698  double sum_log = 0.0;
699  double prod = 1.0;
700  for (MatrixIndexT i = 0; i < dim_; i++) {
701  prod *= data_[i];
702  // Possible future work (arnab): change these magic values to pre-defined
703  // constants
704  if (prod < 1.0e-10 || prod > 1.0e+10) {
705  sum_log += Log(prod);
706  prod = 1.0;
707  }
708  }
709  if (prod != 1.0) sum_log += Log(prod);
710  return sum_log;
711 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
double Log(double x)
Definition: kaldi-math.h:100
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Tanh()

void Tanh ( const VectorBase< Real > &  src)

Sets each element of *this to the tanh of the corresponding element of "src".

Definition at line 900 of file kaldi-vector.cc.

Referenced by VectorBase< float >::ApplyCeiling(), and MatrixBase< float >::Tanh().

900  {
901  KALDI_ASSERT(dim_ == src.dim_);
902  for (MatrixIndexT i = 0; i < dim_; i++) {
903  Real x = src.data_[i];
904  if (x > 0.0) {
905  Real inv_expx = Exp(-x);
906  x = -1.0 + 2.0 / (1.0 + inv_expx * inv_expx);
907  } else {
908  Real expx = Exp(x);
909  x = 1.0 - 2.0 / (1.0 + expx * expx);
910  }
911  data_[i] = x;
912  }
913 }
double Exp(double x)
Definition: kaldi-math.h:83
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Write()

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

Writes to C++ stream (option to write in binary).

Definition at line 1231 of file kaldi-vector.cc.

Referenced by LstmNonlinearityComponent::ConsolidateMemory(), VectorBase< float >::CopyDiagFromTp(), main(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), UnitTestRegressionTree(), AccumFullGmm::Write(), LdaEstimate::Write(), Plda::Write(), RestrictedAttentionComponent::Write(), CuVector< float >::Write(), LstmNonlinearityComponent::Write(), IvectorExtractorStats::Write(), NonlinearComponent::Write(), and kaldi::nnet3::WriteVectorAsChar().

1231  {
1232  if (!os.good()) {
1233  KALDI_ERR << "Failed to write vector to stream: stream not good";
1234  }
1235  if (binary) {
1236  std::string my_token = (sizeof(Real) == 4 ? "FV" : "DV");
1237  WriteToken(os, binary, my_token);
1238 
1239  int32 size = Dim(); // make the size 32-bit on disk.
1240  KALDI_ASSERT(Dim() == (MatrixIndexT) size);
1241  WriteBasicType(os, binary, size);
1242  os.write(reinterpret_cast<const char*>(Data()), sizeof(Real) * size);
1243  } else {
1244  os << " [ ";
1245  for (MatrixIndexT i = 0; i < Dim(); i++)
1246  os << (*this)(i) << " ";
1247  os << "]\n";
1248  }
1249  if (!os.good())
1250  KALDI_ERR << "Failed to write vector to stream";
1251 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:147
Real * Data()
Returns a pointer to the start of the vector&#39;s data.
Definition: kaldi-vector.h:70
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
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
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

Friends And Related Function Documentation

◆ CuVector< Real >

friend class CuVector< Real >
friend

Definition at line 371 of file kaldi-vector.h.

◆ CuVectorBase< Real >

friend class CuVectorBase< Real >
friend

Definition at line 370 of file kaldi-vector.h.

◆ VectorBase< double >

friend class VectorBase< double >
friend

Definition at line 368 of file kaldi-vector.h.

◆ VectorBase< float >

friend class VectorBase< float >
friend

Definition at line 369 of file kaldi-vector.h.

Member Data Documentation

◆ data_

◆ dim_


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