自建机器学习库-矩阵

来源:互联网 发布:如何破解MD5的网络包 编辑:程序博客网 时间:2024/06/06 00:16

推荐一下个人博客

自制一个机器学习库-矩阵

矩阵是机器学习中常用的内容,因此为了建立一个机器学习库,我们从矩阵开始。
机器学习库源码
类名为Matrix,使用模版类。

Matrix<T> tmp;

构造函数

Matrix();无参数,一行,一列,只有一个默认元素。Matrix(long eye);行列均为eye的单位矩阵Matrix(long col, long row, T ele = T());行列分别为col、row元素为默认值的矩阵Matrix(long col, long row, const T *input);行列分别为col、row元素为input数组中元素Matrix(vector<T> const &input);一行的向量,元素为inputMatrix(vector<vector<T>> const &input);n行m列矩阵,元素为input中元素Matrix(Matrix<T> const &m);与m相同的矩阵

矩阵输入输出

Status Show() const;打印矩阵内容vector<vector<T>> GetMat() const;以vector形式返回矩阵元素T Get(long i, long j) const;返回矩阵第i行第j列元素Status Set(long i, long j, T ele);设置矩阵第i行第j列元素为ele,改变原矩阵值long GetColumn() const;返回矩阵行数long GetRow() const;返回矩阵列数

矩阵基本运算

以下均为改变原矩阵

Status SwitchColumn(long i1, long i2);交换i1行和i2行Status SwitchRow(long j1, long j2);交换j1列和j2列Status MultiplyColumn(long i, double multiplier);将矩阵i行乘以multiplierStatus MultiplyRow(long j, double multiplier);将矩阵j列乘以multiplierStatus AddColumn(long i1, double multiplier, long i2);将矩阵i1行乘以multiplier加到i2行Status AddRow(long j1, double multiplier, long j2);将矩阵j1列乘以multiplier加到j2列

运算符重载

Matrix<T> operator=(Matrix<T> const &m);矩阵赋值返回右值vector<T> operator[](long index) const;取第index行friend bool operator==(Matrix<T> const &m1, Matrix<T> const &m2)判断矩阵相等以下均为对应元素运算friend Matrix<T> operator+(Matrix<T> const &m1, Matrix<T> const &m2)矩阵加friend Matrix<T> operator*(T const &m1, Matrix<T> const &m2)数乘矩阵friend Matrix<T> operator-(Matrix<T> const &m1, Matrix<T> const &m2)矩阵减friend Matrix<T> operator*(Matrix<T> const &m1, Matrix<T> const &m2)矩阵乘friend Matrix<T> operator/(Matrix<T> const &m1, Matrix<T> const &m2)矩阵除Matrix<T> operator-() const;矩阵负

矩阵常用运算

以下均不改变原矩阵值,返回一个新矩阵

Matrix<T> SubMatrix(long start_col, long end_col, long start_row, long end_row) const;返回一个子矩阵Matrix<T> Cofactor(long x, long y) const;返回去掉第x行和第y列的矩阵Matrix<T> RowEchelon(long *swap = nullptr) const;返回一个行阶梯形矩阵,其中可选参数swap为基本行运算次数Matrix<T> Cat(Matrix<T> const &m) const;连接两个行数相同矩阵bool IsInversible() const;判断矩阵是否可逆double Det() const;矩阵的行列式Matrix<T> Transpose() const;矩阵的转置Matrix<T> Dot(Matrix<T> const &m) const;矩阵点乘 *this*mMatrix<T> Inverse() const;求矩阵的逆T Tr() const;矩阵的迹long Rank() const;矩阵的秩double NormVector(long p) const;只有当矩阵为一行/列时可用,求p范数Matrix<T> Schmidt() const;施密特正交化Matrix<T> GramSchmidt() const;施密特单位正交化Matrix<T> QR() const;// return Q对矩阵进行QR分解返回Q矩阵vector<T> Eigen() const;返回矩阵特征值Matrix<T> Shuffle() const;将矩阵按行随机排列
原创粉丝点击