fix error 0.5 and add math pdf
This commit is contained in:
81
tests/compare_scalar_matrix.cpp
Normal file
81
tests/compare_scalar_matrix.cpp
Normal file
@@ -0,0 +1,81 @@
|
||||
// Сверка двух реализаций одного шага обучения:
|
||||
// linear (развёрнутые скалярные формулы) и matrix (матричные операции).
|
||||
// Обе реализации должны давать одинаковые веса, ошибку и выход.
|
||||
|
||||
#include "linear/linear.hpp"
|
||||
#include "matrix/matrix.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
namespace
|
||||
{
|
||||
bool close(float a, float b, float eps = 1e-5f)
|
||||
{
|
||||
const float scale = std::max(1.0f, std::max(std::fabs(a), std::fabs(b)));
|
||||
return std::fabs(a - b) <= eps * scale;
|
||||
}
|
||||
|
||||
int check(float a, float b, const char* name, std::size_t i, std::size_t j)
|
||||
{
|
||||
if (close(a, b)) return 0;
|
||||
|
||||
std::cerr << name << "[" << i << "][" << j << "]: scalar=" << a
|
||||
<< ", matrix=" << b << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// run() обеих реализаций печатает промежуточные значения; для теста
|
||||
// отправляем этот вывод в буфер, чтобы в лог попадал только результат.
|
||||
std::ostringstream sink;
|
||||
auto* old_buf = std::cout.rdbuf(sink.rdbuf());
|
||||
|
||||
const auto scalar = linear::run();
|
||||
const auto matrix = matrix::run();
|
||||
|
||||
std::cout.rdbuf(old_buf);
|
||||
|
||||
int failures = 0;
|
||||
|
||||
for (std::size_t i = 0; i < 3; ++i)
|
||||
{
|
||||
for (std::size_t j = 0; j < 3; ++j)
|
||||
{
|
||||
failures += check(scalar.W_1[i][j], matrix.W_1(i, j), "W1", i, j);
|
||||
failures += check(scalar.W_2[i][j], matrix.W_2(i, j), "W2", i, j);
|
||||
}
|
||||
}
|
||||
|
||||
if (!close(scalar.error, matrix.error))
|
||||
{
|
||||
std::cerr << "error: scalar=" << scalar.error
|
||||
<< ", matrix=" << matrix.error << '\n';
|
||||
++failures;
|
||||
}
|
||||
|
||||
for (std::size_t j = 0; j < 3; ++j)
|
||||
{
|
||||
if (!close(scalar.out[j], matrix.out(j, 0)))
|
||||
{
|
||||
std::cerr << "out[" << j << "]: scalar=" << scalar.out[j]
|
||||
<< ", matrix=" << matrix.out(j, 0) << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
if (failures != 0)
|
||||
{
|
||||
std::cerr << "--- captured run output ---\n" << sink.str() << "\n";
|
||||
std::cerr << failures << " mismatches\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::cout << "scalar vs matrix: OK\n";
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user