Being a bit curious about machine learning, I have started reading some introductory tutorials related to that topic. Due to this, some days ago I found a very simple neural network example, implemented using Python with the numpy
library and for practicing purposes, I decided to implement the same algorithm using C++ with as less as possible external libraries.
Then, I first coded a simple class able to handle matrix definitions/declarations and related mathematical operations like addition, multiplication, etc. I eloquently named that class as Matrix
.
Here is its header file:
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;
};
As you can see, in order to allocate the right memory size, I decided to let the class constructor need two different arguments, that is number of rows and columns.
Anyway, after the definition of this briefly explained class, I started to code the main class for the network implementation. In particular, this more abstract class will mainly use the Matrix
class for most of the operations. Here is the header:
#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;
};
Despite it is not properly elegant, also this class constructor takes two input parameters related to matrices: that is because they will be used to correctly instantiate a matrix inside the class for the weighting coefficient storage.
And here is the issue: the mentioned matrix should be definitely instantiated after the initialisation of the Neuron
class. As far as I know, this kind of operation requires the utilisation of a pointer which will be referred by the new
function, used - on its side - to dynamically instantiate a Matrix
class, in this case. However, on the other side, I have decided that operations with matrices always returns a new matrix and not a pointer to matrix, as you can see in the first class header.
So, I am going to ask you: is it possible to define a matrix inside the Neuron
constructor and use it as a class variable, as defined in the previous header? In this way, I should be able to overwrite the same variable when doing operations on the weights
named matrix.
If yes, how can I do this?