mirror of
https://github.com/PaddlePaddle/FastDeploy.git
synced 2025-10-05 16:48:03 +08:00
Update cosine_similarity.cc
This commit is contained in:

committed by
XieYunshen

parent
c521c6ae4c
commit
b8a54dbf57
@@ -23,24 +23,19 @@ float CosineSimilarity(const std::vector<float>& a, const std::vector<float>& b,
|
|||||||
FDASSERT((a.size() == b.size()) && (a.size() != 0),
|
FDASSERT((a.size() == b.size()) && (a.size() != 0),
|
||||||
"The size of a and b must be equal and >= 1.");
|
"The size of a and b must be equal and >= 1.");
|
||||||
size_t num_val = a.size();
|
size_t num_val = a.size();
|
||||||
|
float mul_ab = 0.f;
|
||||||
if (normalized) {
|
if (normalized) {
|
||||||
float mul_a = 0.f, mul_b = 0.f, mul_ab = 0.f;
|
|
||||||
for (size_t i = 0; i < num_val; ++i) {
|
for (size_t i = 0; i < num_val; ++i) {
|
||||||
mul_a += (a[i] * a[i]);
|
|
||||||
mul_b += (b[i] * b[i]);
|
|
||||||
mul_ab += (a[i] * b[i]);
|
mul_ab += (a[i] * b[i]);
|
||||||
}
|
}
|
||||||
return (mul_ab / (std::sqrt(mul_a) * std::sqrt(mul_b)));
|
return mul_ab;
|
||||||
}
|
}
|
||||||
auto norm_a = L2Normalize(a);
|
auto norm_a = L2Normalize(a);
|
||||||
auto norm_b = L2Normalize(b);
|
auto norm_b = L2Normalize(b);
|
||||||
float mul_a = 0.f, mul_b = 0.f, mul_ab = 0.f;
|
|
||||||
for (size_t i = 0; i < num_val; ++i) {
|
for (size_t i = 0; i < num_val; ++i) {
|
||||||
mul_a += (norm_a[i] * norm_a[i]);
|
|
||||||
mul_b += (norm_b[i] * norm_b[i]);
|
|
||||||
mul_ab += (norm_a[i] * norm_b[i]);
|
mul_ab += (norm_a[i] * norm_b[i]);
|
||||||
}
|
}
|
||||||
return (mul_ab / (std::sqrt(mul_a) * std::sqrt(mul_b)));
|
return mul_ab;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace utils
|
} // namespace utils
|
||||||
|
Reference in New Issue
Block a user