【发布时间】:2018-02-28 02:01:41
【问题描述】:
由于对机器学习有点好奇,我开始阅读一些与该主题相关的入门教程。因此,几天前我发现了一个非常简单的神经网络示例,使用 Python 和 numpy 库实现,出于练习目的,我决定使用 C++ 实现相同的算法,并尽可能少地使用外部库。
然后,我首先编写了一个简单的类,该类能够处理矩阵定义/声明和相关的数学运算,如加法、乘法等。我雄辩地将该类命名为Matrix。
这是它的头文件:
template <typename T>
class Matrix {
public:
Matrix(int numRows, int numColumns);
~Matrix();
int getRows();
int getColumns();
T readValue(int row, int column);
void writeValue(int row, int column, T value);
Matrix<T> operator+(Matrix<T> other);
Matrix<T> operator-(Matrix<T> other);
Matrix<T> operator*(T scalar);
Matrix<T> operator*(Matrix<T> other);
Matrix<T> entrywiseProduct(Matrix<T> other);
Matrix<T> transpose();
void print();
private:
const int rows;
const int columns;
T** matrix;
};
如您所见,为了分配正确的内存大小,我决定让类构造函数需要两个不同的参数,即行数和列数。
无论如何,在定义了这个简单解释的类之后,我开始编写网络实现的主类。特别是,这个更抽象的类将主要使用Matrix 类进行大部分操作。这是标题:
#include "Matrix.h"
template <typename T>
class Neuron {
public:
Neuron(int matrixRows, int matrixColumns);
~Neuron();
Matrix<T> estimate(Matrix<T> inputMatrix);
void train(Matrix<T> inputMatrix, Matrix<T> outputMatrix, int iterations);
private:
Matrix<T> weights;
};
尽管它不够优雅,但这个类的构造函数也接受了两个与矩阵相关的输入参数:那是因为它们将用于在类内正确实例化一个矩阵以存储加权系数。
这就是问题所在:在Neuron 类的初始化之后肯定应该实例化所提到的矩阵。据我所知,这种操作需要使用一个指针,该指针将由new 函数引用,在这种情况下,用于动态实例化Matrix 类。然而,另一方面,我已经决定使用矩阵的操作总是返回一个新矩阵而不是指向矩阵的指针,正如您在第一个类标题中看到的那样。
所以,我要问你:是否可以在Neuron 构造函数中定义一个矩阵并将其用作类变量,如上一个标题中定义的那样?这样,在weights命名矩阵上进行操作时,我应该能够覆盖相同的变量。
如果是,我该怎么做?
【问题讨论】:
-
推荐阅读What is the Rule of Three?,以防止将来出现一些讨厌的调试。当您使用它时,请熟悉它的同伴Rules of Zero and Five.