188 lines
6.2 KiB
C++
188 lines
6.2 KiB
C++
#pragma once
|
||
|
||
#include <vector>
|
||
#include <cmath>
|
||
#include <initializer_list>
|
||
#include <cstddef>
|
||
#include <type_traits>
|
||
#include <iostream>
|
||
#include <iomanip>
|
||
#include <string>
|
||
#include <cassert>
|
||
#include <stdexcept>
|
||
#include <hack/logger/logger.hpp>
|
||
|
||
#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<std::size_t Rows, std::size_t Cols, typename Type = float>
|
||
class matrix
|
||
{
|
||
static_assert(std::is_arithmetic_v<Type> && !std::is_same_v<Type, bool>,
|
||
"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<std::initializer_list<Type>> 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<std::size_t C>
|
||
matrix<Rows, C, Type> operator*(const matrix<Cols, C, Type>& rm) const
|
||
{
|
||
matrix<Rows, C, Type> 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<typename Activation>
|
||
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<Cols, Rows, Type> transpose() const
|
||
{
|
||
matrix<Cols, Rows, Type> 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<Type> m_data;
|
||
};
|
||
|
||
// применяем эта если нужно оставить промежуточные результаты
|
||
// Условие совместимости:
|
||
// A (Rows × Cols) * B (R × C) = C (Rows × C)
|
||
// столбцы A = строки B
|
||
// т.е. входящая метрица на которую умножеем должна иметь Cols строк
|
||
// rm: Cols × C
|
||
// *this: Rows × Cols
|
||
// result: Rows × C
|
||
template<std::size_t Rows, std::size_t Cols, std::size_t C, typename Type>
|
||
inline matrix<Rows, C, Type> operator*(const matrix<Rows, Cols, Type>& a, const matrix<Cols, C, Type>& b)
|
||
{
|
||
matrix<Rows, C, Type> 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<std::size_t Rows, std::size_t Cols, typename Type, typename Activation>
|
||
inline matrix<Rows, Cols, Type> apply(const matrix<Rows, Cols, Type>& m, Activation func)
|
||
{
|
||
matrix<Rows, Cols, Type> 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;
|
||
}
|
||
}
|