From a526a31d00a9a8f883d80b734a4ca6064425d290 Mon Sep 17 00:00:00 2001 From: Ryan Curtin Date: Mon, 9 Feb 2015 11:41:17 -0500 Subject: [PATCH] Code cleanup; better documentation. --- .../methods/amf/init_rules/average_init.hpp | 59 +++++++++++-------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/src/mlpack/methods/amf/init_rules/average_init.hpp b/src/mlpack/methods/amf/init_rules/average_init.hpp index cf01ce4228..77376686b5 100644 --- a/src/mlpack/methods/amf/init_rules/average_init.hpp +++ b/src/mlpack/methods/amf/init_rules/average_init.hpp @@ -13,51 +13,64 @@ namespace mlpack { namespace amf { /** - * This initialization rule initializes matrix W and H to root of average of V - * with uniform noise. Uniform noise is generated by Armadillo's 'randu' function. - * To have a better effect lower bound of the matrix is subtracted from average - * before dividing it by the factorization rank. This computed value is added - * with the random noise. - */ + * This initialization rule initializes matrix W and H to root of the average of + * V, perturbed with uniform noise. Uniform noise is generated by Armadillo's + * 'randu' function. For better performance, the lowest element of the matrix + * is subtracted from the average before dividing it by the factorization rank. + * This computed value is added with the random noise. + */ class AverageInitialization { public: // Empty constructor required for the InitializeRule template AverageInitialization() { } + /** + * Initialize the matrices W and H to the average value of V with uniform + * random noise added. + */ + * @param V Input matrix. + * @param r Rank of matrix. + * @param W W matrix, to be initialized. + * @param H H matrix, to be initialized. + */ template inline static void Initialize(const MatType& V, const size_t r, arma::mat& W, arma::mat& H) { - size_t n = V.n_rows; - size_t m = V.n_cols; - - double V_avg = 0; + const size_t n = V.n_rows; + const size_t m = V.n_cols; + + double avgV = 0; size_t count = 0; double min = DBL_MAX; - for(typename MatType::const_row_col_iterator it = V.begin();it != V.end();it++) + + // Iterate over all elements in the matrix (for sparse matrices, this only + // iterates over nonzeros). + for (typename MatType::const_row_col_iterator it = V.begin(); + it != V.end(); ++it) { - if(*it != 0) - { - count++; - V_avg += *it; - if(*it < min) min = *it; - } + ++count; + avgV += *it; + // Track the minimum value. + if (*it < min) + min = *it; } - V_avg = sqrt(((V_avg / (n * m)) - min) / r); + + V_avg = sqrt(((avgV / (n * m)) - min) / r); // Intialize to random values. W.randu(n, r); H.randu(r, m); - - W = W + V_avg; - H = H + V_avg; + + W = W + avgV; + H = H + avgV; } }; -}; // namespace amf -}; // namespace mlpack +} // namespace amf +} // namespace mlpack #endif