NNFS
Neural network library from scratch
Loading...
Searching...
No Matches
Softmax.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "Activation.hpp"
4
5namespace NNFS
6{
12 class Softmax : public Activation
13 {
14 public:
15 Eigen::MatrixXd _forward_output; // Output data for forward pass
16
17 public:
22
29 void forward(Eigen::MatrixXd &out, const Eigen::MatrixXd &x) override
30 {
32 equation(out, x);
33 _forward_output = out;
34 }
35
42 void backward(Eigen::MatrixXd &out, const Eigen::MatrixXd &dx) override
43 {
44 // Create uninitialized array
45 out.resizeLike(dx);
46
47 for (int i = 0; i < _forward_output.rows(); i++)
48 {
49
50 Eigen::MatrixXd single_output = _forward_output.row(i).transpose();
51
52 Eigen::MatrixXd jacobian_matrix = Eigen::MatrixXd::Zero(_forward_output.cols(), _forward_output.cols());
53 for (int j = 0; j < _forward_output.cols(); ++j)
54 {
55 jacobian_matrix(j, j) = single_output(j, 0);
56 }
57 jacobian_matrix -= single_output * single_output.transpose();
58
59 out.row(i) = jacobian_matrix * dx.row(i).transpose();
60 }
61 }
62
69 void equation(Eigen::MatrixXd &out, const Eigen::MatrixXd &x)
70 {
71 Eigen::MatrixXd expX = x;
72 for (int i = 0; i < expX.rows(); i++)
73 {
74 double max_val = expX.row(i).maxCoeff();
75 expX.row(i) -= Eigen::VectorXd::Constant(expX.cols(), max_val);
76 }
77
78 expX = expX.array().exp();
79 out = x;
80 for (int row = 0; row < x.rows(); ++row)
81 {
82 out.row(row) = expX.row(row) / expX.row(row).sum();
83 }
84 }
85 };
86} // namespace NNFS
Base class for all activation functions.
Definition Activation.hpp:24
Eigen::MatrixXd _forward_input
Definition Activation.hpp:37
Softmax activation function.
Definition Softmax.hpp:13
void equation(Eigen::MatrixXd &out, const Eigen::MatrixXd &x)
Softmax equation.
Definition Softmax.hpp:69
void backward(Eigen::MatrixXd &out, const Eigen::MatrixXd &dx) override
Backward pass of the softmax activation function.
Definition Softmax.hpp:42
Softmax()
Construct a new Softmax object.
Definition Softmax.hpp:21
void forward(Eigen::MatrixXd &out, const Eigen::MatrixXd &x) override
Forward pass of the softmax activation function.
Definition Softmax.hpp:29
Eigen::MatrixXd _forward_output
Definition Softmax.hpp:15
Definition Activation.hpp:6
ActivationType
Enum class for activation types.
Definition Activation.hpp:11