Files
nn_rashid/tests/compare_scalar_matrix.cpp

82 lines
2.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Сверка двух реализаций одного шага обучения:
// 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;
}