FlexNN 1
Fully connected neural network built from scratch with flexible n-layer design and multiple activations.
Loading...
Searching...
No Matches
Softmax.hpp
Go to the documentation of this file.
1
11#pragma once
12
13#include <Eigen/Dense>
14
16
23inline Eigen::MatrixXd softmax_forward(const Eigen::MatrixXd& Z) {
24 Eigen::MatrixXd A(Z.rows(), Z.cols());
25 for (Eigen::Index c = 0; c < Z.cols(); ++c) {
26 Eigen::VectorXd col = Z.col(c);
27 double m = col.maxCoeff();
28 Eigen::VectorXd e = (col.array() - m).exp();
29 A.col(c) = e / e.sum();
30 }
31 return A;
32}
33
46inline Eigen::MatrixXd softmax_backward_hidden(const Eigen::MatrixXd& s,
47 const Eigen::MatrixXd& upstream) noexcept {
48 Eigen::MatrixXd dZ(s.rows(), s.cols());
49 for (Eigen::Index c = 0; c < s.cols(); ++c) {
50 Eigen::VectorXd sv = s.col(c);
51 Eigen::VectorXd up = upstream.col(c);
52 double dot = sv.dot(up); // s^T * up (scalar per column)
53 // J*up = diag(s)*up - s*(s^T*up) = s ⊙ up - s*dot = s ⊙ (up - dot)
54 dZ.col(c) = sv.array() * up.array() - sv.array() * dot;
55 }
56 return dZ;
57}
58
59} // namespace FlexNN::Activations::detail
Definition Activation.hpp:81
Eigen::MatrixXd softmax_forward(const Eigen::MatrixXd &Z)
Stable column-wise softmax forward.
Definition Softmax.hpp:23
Eigen::MatrixXd softmax_backward_hidden(const Eigen::MatrixXd &s, const Eigen::MatrixXd &upstream) noexcept
Softmax hidden backward: dZ = J * upstream per column.
Definition Softmax.hpp:46