NumCpp  2.5.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
softmax.hpp
Go to the documentation of this file.
1 #pragma once
29 
32 #include "NumCpp/Core/Types.hpp"
33 #include "NumCpp/Functions/exp.hpp"
34 #include "NumCpp/NdArray.hpp"
35 
36 namespace nc
37 {
38  namespace special
39  {
40  //============================================================================
41  // Method Description:
51  template<typename dtype>
53  {
55 
56  switch (inAxis)
57  {
58  case Axis::NONE:
59  {
60  auto returnArray = exp(inArray).template astype<double>();
61  returnArray /= static_cast<double>(returnArray.sum().item());
62  return returnArray;
63  }
64  case Axis::COL:
65  {
66  auto returnArray = exp(inArray).template astype<double>();
67  auto expSums = returnArray.sum(inAxis);
68 
69  for (uint32 row = 0; row < returnArray.shape().rows; ++row)
70  {
71  const auto rowExpSum = static_cast<double>(expSums[row]);
72  stl_algorithms::for_each(returnArray.begin(row), returnArray.end(row),
73  [rowExpSum](double& value) { value /= rowExpSum; });
74  }
75 
76  return returnArray;
77  }
78  case Axis::ROW:
79  {
80  auto returnArray = exp(inArray.transpose()).template astype<double>();
81  auto expSums = returnArray.sum(Axis::COL);
82 
83  for (uint32 row = 0; row < returnArray.shape().rows; ++row)
84  {
85  const auto rowExpSum = static_cast<double>(expSums[row]);
86  stl_algorithms::for_each(returnArray.begin(row), returnArray.end(row),
87  [rowExpSum](double& value) { value /= rowExpSum; });
88  }
89 
90  return returnArray.transpose();
91  }
92  default:
93  {
94  THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type.");
95  return {}; // get rid of compiler warning
96  }
97  }
98  }
99  } // namespace special
100 } // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition: StaticAsserts.hpp:37
NdArray< dtype > transpose() const
Definition: NdArrayCore.hpp:4830
NdArray< double > softmax(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition: softmax.hpp:52
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:213
Definition: Coordinate.hpp:45
Axis
Enum To describe an axis.
Definition: Types.hpp:46
auto exp(dtype inValue) noexcept
Definition: exp.hpp:51
std::uint32_t uint32
Definition: Types.hpp:40