diff --git a/math/Рашид.pdf b/math/Рашид.pdf new file mode 100644 index 0000000..d355b27 Binary files /dev/null and b/math/Рашид.pdf differ diff --git a/meson.build b/meson.build index fa91e26..cc3d74d 100755 --- a/meson.build +++ b/meson.build @@ -46,3 +46,4 @@ deps = [ subdir('src') subdir('bin') +subdir('tests') diff --git a/src/linear/linear.hpp b/src/linear/linear.hpp index 32301e8..418ad73 100644 --- a/src/linear/linear.hpp +++ b/src/linear/linear.hpp @@ -2,6 +2,7 @@ #include #include "utils.hpp" +#include #include // Линейная форма - это прямой расчет прохода ошибки по математиченским формулам. @@ -26,7 +27,16 @@ namespace linear return 1.0 / (1 + r); } - inline void run() + // Результат одного шага: новые веса, ошибка и выход сети. + struct result + { + utils::matrix_leaner W_1; + utils::matrix_leaner W_2; + float error; + std::array out; + }; + + inline result run() { std::vector Inp = { 1.0, 2.0, 3.0 }; std::vector T = { 0.1, 0.2, 0.3 }; @@ -100,10 +110,11 @@ namespace linear hack::log()("Out 2 =", Out_2); hack::log()("Out 3 =", Out_3); - // Ошибка - auto E_1 = std::pow((Out_1 - T[0]), 2); - auto E_2 = std::pow((Out_2 - T[1]), 2); - auto E_3 = std::pow((Out_3 - T[2]), 2); + // Ошибка: E = (1/2) * sum((Out_j - T_j)^2), как в конспекте. + const float E_1 = 0.5f * (Out_1 - T[0]) * (Out_1 - T[0]); + const float E_2 = 0.5f * (Out_2 - T[1]) * (Out_2 - T[1]); + const float E_3 = 0.5f * (Out_3 - T[2]) * (Out_3 - T[2]); + const float E = E_1 + E_2 + E_3; hack::log()(); hack::log()("Ошибка"); @@ -111,12 +122,13 @@ namespace linear hack::log()("E 1 =", E_1); hack::log()("E 2 =", E_2); hack::log()("E 3 =", E_3); + hack::log()("E =", E); // ОБРАТНЫЙ ПРОХОД (backward) // Вклад нейрона в ошибку (дельта) - auto delta_1_2 = 2 * (Out_1 - T[0]) * Out_1 * (1 - Out_1); - auto delta_2_2= 2 * (Out_2 - T[1]) * Out_2 * (1 - Out_2); - auto delta_3_2 = 2 * (Out_3 - T[2]) * Out_3 * (1 - Out_3); + const float delta_1_2 = (Out_1 - T[0]) * Out_1 * (1.0f - Out_1); + const float delta_2_2 = (Out_2 - T[1]) * Out_2 * (1.0f - Out_2); + const float delta_3_2 = (Out_3 - T[2]) * Out_3 * (1.0f - Out_3); hack::log()(); hack::log()("========================="); @@ -296,5 +308,7 @@ namespace linear hack::log()(W_2[0]); hack::log()(W_2[1]); hack::log()(W_2[2]); + + return { W_1, W_2, E, { Out_1, Out_2, Out_3 } }; } } diff --git a/src/matrix/matrix.hpp b/src/matrix/matrix.hpp index e05d0e9..661f273 100644 --- a/src/matrix/matrix.hpp +++ b/src/matrix/matrix.hpp @@ -24,7 +24,16 @@ namespace matrix { 1.2, 1.5, 1.8 } }; - inline void run() + // Результат одного шага: новые веса, ошибка и выход сети. + struct result + { + utils::matrix<3, 3> W_1; + utils::matrix<3, 3> W_2; + float error; + utils::matrix<3, 1> out; + }; + + inline result run() { // ================================================= // ПРЯМОЙ ПРОХОД (forward) @@ -50,7 +59,7 @@ namespace matrix hack::log()("Error 2 = ", Err_2); hack::log()("Error 3 = ", Err_3); - auto Err = 0.5 * (SQR(Err_1) + SQR(Err_2) + SQR(Err_3)); + const float Err = 0.5f * (SQR(Err_1) + SQR(Err_2) + SQR(Err_3)); hack::log()("ERROR = ", Err); // ================================================= @@ -99,5 +108,6 @@ namespace matrix auto W_2_new = W_2 - delta_Out.transpose() * Int.transpose() * utils::LEARNING_RATE; W_2_new.print("W 2 new"); + return { W_1_new, W_2_new, Err, Out }; } } diff --git a/tests/compare_scalar_matrix.cpp b/tests/compare_scalar_matrix.cpp new file mode 100644 index 0000000..c3dc1b0 --- /dev/null +++ b/tests/compare_scalar_matrix.cpp @@ -0,0 +1,81 @@ +// Сверка двух реализаций одного шага обучения: +// linear (развёрнутые скалярные формулы) и matrix (матричные операции). +// Обе реализации должны давать одинаковые веса, ошибку и выход. + +#include "linear/linear.hpp" +#include "matrix/matrix.hpp" + +#include +#include +#include +#include +#include + +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; +} diff --git a/tests/meson.build b/tests/meson.build new file mode 100644 index 0000000..3f2a560 --- /dev/null +++ b/tests/meson.build @@ -0,0 +1,8 @@ +compare_scalar_matrix = executable( + 'compare_scalar_matrix', + 'compare_scalar_matrix.cpp', + dependencies : deps, + include_directories : inc, +) + +test('compare_scalar_matrix', compare_scalar_matrix)