NNFS
Neural network library from scratch
Loading...
Searching...
No Matches
CCE_Softmax.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "CCE.hpp"
4#include "../Activation/Softmax.hpp"
5
6namespace NNFS
7{
13 class CCESoftmax : public Loss
14 {
15 public:
22 CCESoftmax(std::shared_ptr<Softmax> softmax, std::shared_ptr<CCE> cce) : Loss(LossType::CCE_SOFTMAX), _softmax(softmax), _cce(cce) {}
23
31 void forward(Eigen::MatrixXd &sample_losses, const Eigen::MatrixXd &predictions, const Eigen::MatrixXd &labels) const
32 {
33 Eigen::MatrixXd out;
34
35 _softmax->forward(out, predictions);
36
37 _cce->forward(sample_losses, out, labels);
38 }
39
47 void backward(Eigen::MatrixXd &out, const Eigen::MatrixXd &predictions, const Eigen::MatrixXd &labels) const
48 {
49 Eigen::MatrixXd _predictions = softmax_out();
50 int samples = predictions.rows();
51
52 Eigen::VectorXi class_labels(labels.rows());
53 for (int k = 0; k < labels.rows(); ++k)
54 {
55 labels.row(k).maxCoeff(&class_labels[k]);
56 };
57
58 out = _predictions;
59
60 // Calculate gradient
61 for (int i = 0; i < samples; i++)
62 {
63 int index = class_labels(i);
64 out(i, index) -= 1;
65 }
66
67 // Normalize gradient
68 out /= samples;
69 }
70
76 Eigen::MatrixXd &softmax_out() const
77 {
78 return _softmax->_forward_output;
79 }
80
81 private:
82 std::shared_ptr<Softmax> _softmax; // Softmax activation layer
83 std::shared_ptr<CCE> _cce; // Cross-entropy loss function
84 Eigen::MatrixXd _softmax_out; // Softmax output
85 };
86} // namespace NNFS
Cross-entropy loss function with softmax activation.
Definition CCE_Softmax.hpp:14
CCESoftmax(std::shared_ptr< Softmax > softmax, std::shared_ptr< CCE > cce)
Construct a new CCESoftmax object.
Definition CCE_Softmax.hpp:22
Eigen::MatrixXd & softmax_out() const
Get the softmax output.
Definition CCE_Softmax.hpp:76
void forward(Eigen::MatrixXd &sample_losses, const Eigen::MatrixXd &predictions, const Eigen::MatrixXd &labels) const
Forward pass of the CCE loss function with softmax activation.
Definition CCE_Softmax.hpp:31
void backward(Eigen::MatrixXd &out, const Eigen::MatrixXd &predictions, const Eigen::MatrixXd &labels) const
Backward pass of the CCE loss function with softmax activation.
Definition CCE_Softmax.hpp:47
Base class for all loss functions.
Definition Loss.hpp:24
Definition Activation.hpp:6
LossType
Enum class for loss types.
Definition Loss.hpp:13