mlpack
normalize_labels_impl.hpp
Go to the documentation of this file.
1 
13 #ifndef MLPACK_CORE_DATA_NORMALIZE_LABELS_IMPL_HPP
14 #define MLPACK_CORE_DATA_NORMALIZE_LABELS_IMPL_HPP
15 
16 // In case it hasn't been included yet.
17 #include "normalize_labels.hpp"
18 
19 namespace mlpack {
20 namespace data {
21 
32 template<typename eT, typename RowType>
33 void NormalizeLabels(const RowType& labelsIn,
34  arma::Row<size_t>& labels,
35  arma::Col<eT>& mapping)
36 {
37  // Loop over the input labels, and develop the mapping. We'll first naively
38  // resize the mapping to the maximum possible size, and then when we fill it,
39  // we'll resize it back down to its actual size.
40  mapping.set_size(labelsIn.n_elem);
41  labels.set_size(labelsIn.n_elem);
42  // Map for mapping labelIn to their label.
43  std::unordered_map<eT, size_t> labelMap;
44  size_t curLabel = 0;
45  for (size_t i = 0; i < labelsIn.n_elem; ++i)
46  {
47  // If labelsIn[i] is already in the map, use the existing label.
48  if (labelMap.count(labelsIn[i]) > 0)
49  {
50  labels[i] = labelMap[labelsIn[i]];
51  }
52  else
53  {
54  // If labelsIn[i] not there then add it to map.
55  labelMap[labelsIn[i]] = curLabel;
56  labels[i] = curLabel;
57  ++curLabel;
58  }
59  }
60  // Resize mapping back down to necessary size.
61  mapping.resize(curLabel);
62  // Mapping array created with encoded labels.
63  for (auto it = labelMap.begin(); it != labelMap.end(); ++it)
64  {
65  mapping[it->second] = it->first;
66  }
67 }
68 
77 template<typename eT>
78 void RevertLabels(const arma::Row<size_t>& labels,
79  const arma::Col<eT>& mapping,
80  arma::Row<eT>& labelsOut)
81 {
82  // We already have the mapping, so we just need to loop over each element.
83  labelsOut.set_size(labels.n_elem);
84 
85  for (size_t i = 0; i < labels.n_elem; ++i)
86  labelsOut[i] = mapping[labels[i]];
87 }
88 
89 } // namespace data
90 } // namespace mlpack
91 
92 #endif
void NormalizeLabels(const RowType &labelsIn, arma::Row< size_t > &labels, arma::Col< eT > &mapping)
Given a set of labels of a particular datatype, convert them to unsigned labels in the range [0...
Definition: normalize_labels_impl.hpp:33
Linear algebra utility functions, generally performed on matrices or vectors.
Definition: cv.hpp:1
void RevertLabels(const arma::Row< size_t > &labels, const arma::Col< eT > &mapping, arma::Row< eT > &labelsOut)
Given a set of labels that have been mapped to the range [0, n), map them back to the original labels...
Definition: normalize_labels_impl.hpp:78