#pragma once #include #include #include #include #include #include #include #include #include #include #include #define SQR(x) ((x)*(x)) namespace utils { // функции активации. можно добавить еще для поиграться namespace activations { inline auto sigmoid = [](auto x) { using value_type = decltype(x); return value_type{1} / (value_type{1} + std::exp(-x)); }; } namespace derivative { inline auto sigmoid = [](auto x) { using value_type = decltype(x); return x * (value_type{1} - x); }; } // коеффициент обучения inline constexpr float LEARNING_RATE = 0.1f; // i, j - в матрице тут - это как m, n в матрицах в учебниках // т.е. строка и столбец соответственно template class matrix { static_assert(std::is_arithmetic_v && !std::is_same_v, "matrix element type must be arithmetic and not bool"); static_assert(Rows > 0 && Cols > 0, "matrix dimensions must be positive"); public: matrix() : m_data(Rows * Cols, Type{}) {} matrix(Type fill_value) : m_data(Rows * Cols, fill_value) {} matrix(std::initializer_list> init) { if (init.size() != Rows) throw std::invalid_argument("matrix: row count mismatch"); m_data.reserve(Rows * Cols); for (const auto& row : init) { if (row.size() != Cols) throw std::invalid_argument("matrix: column count mismatch"); m_data.insert(m_data.end(), row.begin(), row.end()); } } public: // получаем тут ссылку на элемент матрици // const или не const зависит от нашего контекста Type& operator()(std::size_t i, std::size_t j) { return m_data[i * Cols + j]; } const Type& operator()(std::size_t i, std::size_t j) const { return m_data[i * Cols + j]; } public: // Применяем эти методы если не нужна старая матрица // т.е. нужно сохранить промежуточные результаты: // Условие совместимости: // A (Rows × Cols) * B (R × C) = C (Rows × C) // столбцы A = строки B // т.е. входящая метрица на которую умножеем должна иметь Cols строк // rm: Cols × C // *this: Rows × Cols // result: Rows × C template matrix operator*(const matrix& rm) const { matrix result; for (std::size_t i = 0; i < Rows; ++i) { for (std::size_t k = 0; k < Cols; ++k) { Type a = (*this)(i, k); for (std::size_t j = 0; j < C; ++j) result(i, j) += a * rm(k, j); } } return result; } // Умножение на скаляр matrix operator*(Type scalar) const { matrix result; for (std::size_t i = 0; i < Rows; ++i) for (std::size_t j = 0; j < Cols; ++j) result(i, j) = (*this)(i, j) * scalar; return result; } // Вычитание матриц matrix operator-(const matrix& other) const { matrix result; for (std::size_t i = 0; i < Rows; ++i) for (std::size_t j = 0; j < Cols; ++j) result(i, j) = (*this)(i, j) - other(i, j); return result; } // Применяем это если не нужна старая матрица template matrix& apply(Activation func) { for (std::size_t i = 0; i < Rows; ++i) for (std::size_t j = 0; j < Cols; ++j) (*this)(i, j) = func((*this)(i, j)); return *this; } // Возвращает транспонированную матрицу: (Rows × Cols) -> (Cols × Rows) matrix transpose() const { matrix result; for (std::size_t i = 0; i < Rows; ++i) for (std::size_t j = 0; j < Cols; ++j) result(j, i) = (*this)(i, j); return result; } public: void print(std::string name) const { std::cout << name << ":\n"; for (std::size_t i = 0; i < Rows; ++i) { for (std::size_t j = 0; j < Cols; ++j) std::cout << std::fixed << std::setprecision(8) << (*this)(i, j) << ' '; std::cout << '\n'; } std::cout << '\n'; } private: std::vector m_data; }; // применяем эта если нужно оставить промежуточные результаты // Условие совместимости: // A (Rows × Cols) * B (R × C) = C (Rows × C) // столбцы A = строки B // т.е. входящая метрица на которую умножеем должна иметь Cols строк // rm: Cols × C // *this: Rows × Cols // result: Rows × C template inline matrix operator*(const matrix& a, const matrix& b) { matrix result; for (std::size_t i = 0; i < Rows; ++i) { for (std::size_t k = 0; k < Cols; ++k) { Type aik = a(i, k); for (std::size_t j = 0; j < C; ++j) result(i, j) += aik * b(k, j); } } return result; } // применяем эта если нужно оставить промежуточные результаты template inline matrix apply(const matrix& m, Activation func) { matrix result; for (std::size_t i = 0; i < Rows; ++i) for (std::size_t j = 0; j < Cols; ++j) result(i, j) = func(m(i, j)); return result; } }