NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
svd/svd.hpp
Go to the documentation of this file.
1
29#pragma once
30
31#include <cmath>
32
34#include "NumCpp/Core/Types.hpp"
38#include "NumCpp/Linalg/eig.hpp"
39#include "NumCpp/NdArray.hpp"
40
41namespace nc::linalg
42{
43 // =============================================================================
44 // Class Description:
46 template<typename dtype>
47 class SVD
48 {
49 public:
51
52 static constexpr auto TOLERANCE = 1e-12;
53
54 // =============================================================================
55 // Description:
60 explicit SVD(const NdArray<dtype>& inMatrix) :
61 m_{ inMatrix.shape().rows },
62 n_{ inMatrix.shape().cols },
63 s_(1, m_)
64 {
65 compute(inMatrix.template astype<double>());
66 }
67
68 // =============================================================================
69 // Description:
74 const NdArray<double>& u() const noexcept
75 {
76 return u_;
77 }
78
79 // =============================================================================
80 // Description:
85 const NdArray<double>& v() const noexcept
86 {
87 return v_;
88 }
89
90 // =============================================================================
91 // Description:
96 const NdArray<double>& s() const noexcept
97 {
98 return s_;
99 }
100
101 // =============================================================================
102 // Description:
108 {
109 // lazy evaluation
110 if (pinv_.isempty())
111 {
112 auto sInverse = nc::zeros<double>(n_, m_); // transpose
113 for (auto i = 0u; i < std::min(m_, n_); ++i)
114 {
115 if (s_[i] > TOLERANCE)
116 {
117 sInverse(i, i) = 1. / s_[i];
118 }
119 }
120
121 pinv_ = dot(v_, dot(sInverse, u_.transpose()));
122 }
123
124 return pinv_;
125 }
126
127 // =============================================================================
128 // Description:
136 {
137 if (inInput.size() != m_)
138 {
139 THROW_INVALID_ARGUMENT_ERROR("Invalid matrix dimensions");
140 }
141
142 if (inInput.numCols() == 1)
143 {
144 return dot(pinv(), inInput);
145 }
146 else
147 {
148 const auto input = inInput.copy().reshape(inInput.size(), 1);
149 return dot(pinv(), input);
150 }
151 }
152
153 private:
154 // =============================================================================
155 // Description:
160 void compute(const NdArray<double>& A)
161 {
162 const auto At = A.transpose();
163 const auto AtA = dot(At, A);
164 const auto AAt = dot(A, At);
165
166 const auto& [sigmaSquaredU, U] = eig(AAt);
167 const auto& [sigmaSquaredV, V] = eig(AtA);
168
169 auto rank = 0u;
170 for (auto i = 0u; i < std::min(m_, n_); ++i)
171 {
172 if (sigmaSquaredV[i] > TOLERANCE)
173 {
174 s_[i] = std::sqrt(sigmaSquaredV[i]);
175 rank++;
176 }
177 }
178
179 // std::cout << U.front() << ' ' << U.back() << '\n';
180 // std::cout << V.front() << ' ' << V.back() << '\n';
181 // std::cout << "hello world\n";
182
183 u_ = std::move(U);
184 v_ = std::move(V);
185
186 auto Av = NdArray<double>(m_, 1);
187 for (auto i = 0u; i < rank; ++i)
188 {
189 for (auto j = 0u; j < m_; ++j)
190 {
191 auto sum = 0.;
192 for (auto k = 0u; k < n_; ++k)
193 {
194 sum += A(j, k) * v_(k, i);
195 }
196 Av[j] = sum;
197 }
198
199 const auto normalization = norm(Av).item();
200
201 if (normalization > TOLERANCE)
202 {
203 for (auto j = 0u; j < m_; ++j)
204 {
205 u_(j, i) = Av[j] / normalization;
206 }
207 }
208 }
209 }
210
211 private:
212 // ===============================Attributes====================================
213 const uint32 m_{};
214 const uint32 n_{};
215 NdArray<double> u_{};
216 NdArray<double> v_{};
217 NdArray<double> s_{};
218 NdArray<double> pinv_{};
219 };
220} // namespace nc::linalg
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
size_type size() const noexcept
Definition NdArrayCore.hpp:4600
self_type & reshape(size_type inSize)
Definition NdArrayCore.hpp:4347
self_type transpose() const
Definition NdArrayCore.hpp:4959
size_type numCols() const noexcept
Definition NdArrayCore.hpp:3541
self_type copy() const
Definition NdArrayCore.hpp:2558
value_type item() const
Definition NdArrayCore.hpp:3098
const NdArray< double > & u() const noexcept
Definition svd/svd.hpp:74
const NdArray< double > & s() const noexcept
Definition svd/svd.hpp:96
STATIC_ASSERT_ARITHMETIC(dtype)
static constexpr auto TOLERANCE
Definition svd/svd.hpp:52
NdArray< double > pinv()
Definition svd/svd.hpp:107
SVD(const NdArray< dtype > &inMatrix)
Definition svd/svd.hpp:60
NdArray< double > lstsq(const NdArray< double > &inInput)
Definition svd/svd.hpp:135
const NdArray< double > & v() const noexcept
Definition svd/svd.hpp:85
constexpr auto j
Definition Core/Constants.hpp:42
Definition cholesky.hpp:41
std::pair< NdArray< double >, NdArray< double > > eig(const NdArray< dtype > &inA, double inTolerance=1e-12)
Definition eig.hpp:53
NdArray< double > norm(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition norm.hpp:51
NdArray< dtype > dot(const NdArray< dtype > &inArray1, const NdArray< dtype > &inArray2)
Definition dot.hpp:48
NdArray< dtype > sum(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition sum.hpp:45
NdArray< dtype > zeros(uint32 inSquareSize)
Definition zeros.hpp:48
Shape shape(const NdArray< dtype > &inArray) noexcept
Definition Functions/shape.hpp:42
NdArray< dtypeOut > astype(const NdArray< dtype > inArray)
Definition astype.hpp:43
std::uint32_t uint32
Definition Types.hpp:40