NDArraySimilarity.cpp
Go to the documentation of this file.
1#include "NDArraySimilarity.h"
2
3#include <cstddef>
4#include <cmath>
5
7{
8 float
10 {
11 if (oldValue.getShape() != newValue.getShape())
12 {
13 return 0.0f;
14 }
15
16 const auto oldData = oldValue.getDataAsVector();
17 const auto newData = newValue.getDataAsVector();
18 if (oldData.size() != newData.size())
19 {
20 return 0.0f;
21 }
22
23 double dotProduct = 0.0;
24 double oldSquaredSum = 0.0;
25 double newSquaredSum = 0.0;
26
27 for (size_t i = 0; i < oldData.size(); i++)
28 {
29 const double oldElement = static_cast<double>(oldData.at(i));
30 const double newElement = static_cast<double>(newData.at(i));
31
32 dotProduct += oldElement * newElement;
33 oldSquaredSum += oldElement * oldElement;
34 newSquaredSum += newElement * newElement;
35 }
36
37 const double normProduct = std::sqrt(oldSquaredSum) * std::sqrt(newSquaredSum);
38 if (normProduct == 0.0)
39 {
40 return oldSquaredSum == newSquaredSum ? 1.0f : 0.0f;
41 }
42
43 const double cosineSimilarity = dotProduct / normProduct;
44 const double normalizedSimilarity = (cosineSimilarity / 2.0) + 0.5;
45
46 return static_cast<float>(normalizedSimilarity);
47 }
48}
std::vector< unsigned char > getDataAsVector() const
Definition NDArray.cpp:150
std::vector< int > getShape() const
Definition NDArray.cpp:156
float calculateSimilarity(const aron::data::NDArray &oldValue, const aron::data::NDArray &newValue)