NumCpp  2.8.0
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),
73  returnArray.end(row),
74  [rowExpSum](double& value) { value /= rowExpSum; });
75  }
76 
77  return returnArray;
78  }
79  case Axis::ROW:
80  {
81  auto returnArray = exp(inArray.transpose()).template astype<double>();
82  auto expSums = returnArray.sum(Axis::COL);
83 
84  for (uint32 row = 0; row < returnArray.shape().rows; ++row)
85  {
86  const auto rowExpSum = static_cast<double>(expSums[row]);
87  stl_algorithms::for_each(returnArray.begin(row),
88  returnArray.end(row),
89  [rowExpSum](double& value) { value /= rowExpSum; });
90  }
91 
92  return returnArray.transpose();
93  }
94  default:
95  {
96  THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type.");
97  return {}; // get rid of compiler warning
98  }
99  }
100  }
101  } // namespace special
102 } // 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:4650
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:227
Definition: Coordinate.hpp:45
Axis
Enum To describe an axis.
Definition: Types.hpp:47
auto exp(dtype inValue) noexcept
Definition: exp.hpp:49
std::uint32_t uint32
Definition: Types.hpp:40