Code cleanup; better documentation.

This commit is contained in:
Ryan Curtin
2015-02-09 11:41:17 -05:00
parent d398b95c59
commit a526a31d00
@@ -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<typename MatType>
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