Introduction
On this page, several simple mlpack examples are contained, in increasing order of complexity. If you compile from the command-line, be sure that your compiler is in C++11 mode. With modern gcc and clang, this should already be the default.
- Note
- The command-line programs like
knn_main.cpp
and logistic_regression_main.cpp
from the directory src/mlpack/methods/
cannot be compiled easily by hand (the same is true for the individual tests in src/mlpack/tests/
); instead, those should be compiled with CMake, by running, e.g., make
mlpack_knn
or make
mlpack_test
; see Building mlpack From Source. However, any program that uses mlpack (and is not a part of the library itself) can be compiled easily with g++ or clang from the command line.
Covariance Computation
A simple program to compute the covariance of a data matrix ("data.csv"), assuming that the data is already centered, and save it to file.
int main()
{
arma::mat data;
arma::mat cov = data * trans(data) / data.n_cols;
}
Include all of the base components required to write mlpack methods, and the main mlpack Doxygen docu...
bool Load(const std::string &filename, arma::Mat< eT > &matrix, const bool fatal=false, const bool transpose=true, const arma::file_type inputLoadType=arma::auto_detect)
Loads a matrix from file, guessing the filetype from the extension.
bool Save(const std::string &filename, const arma::Mat< eT > &matrix, const bool fatal=false, bool transpose=true, arma::file_type inputSaveType=arma::auto_detect)
Saves a matrix to file, guessing the filetype from the extension.
Linear algebra utility functions, generally performed on matrices or vectors.
Nearest Neighbor
This simple program uses the mlpack::neighbor::NeighborSearch object to find the nearest neighbor of each point in a dataset using the L1 metric, and then print the index of the neighbor and the distance of it to stdout.
int main()
{
arma::mat data;
NeighborSearch<NearestNeighborSort, ManhattanDistance> nn(data);
arma::Mat<size_t> neighbors;
arma::mat distances;
nn.Search(1, neighbors, distances);
for (size_t i = 0; i < neighbors.n_elem; ++i)
{
std::cout << "Nearest neighbor of point " << i << " is point "
<< neighbors[i] << " and the distance is " << distances[i] << ".\n";
}
}
Other examples
For more complex examples, it is useful to refer to the main executables, found in src/mlpack/methods/
. A few are listed below.
- methods/neighbor_search/knn_main.cpp
- methods/neighbor_search/kfn_main.cpp
- methods/emst/emst_main.cpp
- methods/radical/radical_main.cpp
- methods/nca/nca_main.cpp
- methods/naive_bayes/nbc_main.cpp
- methods/pca/pca_main.cpp
- methods/lars/lars_main.cpp
- methods/linear_regression/linear_regression_main.cpp
- methods/gmm/gmm_main.cpp
- methods/kmeans/kmeans_main.cpp