diff --git a/matrix.h b/matrix.h index 6cf95ae..c91f512 100644 --- a/matrix.h +++ b/matrix.h @@ -7,7 +7,7 @@ typedef float MatrixType; typedef struct { - MatrixType **data; + MatrixType *buffer; unsigned int rows; unsigned int cols; } Matrix; diff --git a/neuralNetwork.h b/neuralNetwork.h index 7f06607..599bc04 100644 --- a/neuralNetwork.h +++ b/neuralNetwork.h @@ -1,9 +1,15 @@ #ifndef NEURALNETWORK_H #define NEURALNETWORK_H +#define checkFileHeader image_input_check_file_header_guard +#define readDimension image_input_read_dimension_guard #include "imageInput.h" +#undef checkFileHeader +#undef readDimension #include "matrix.h" +#define NEURAL_NETWORK_FILE_HEADER "__info2_neural_network_file_format__" + typedef void (*ActivationFunctionType)(Matrix *X); typedef struct diff --git a/neuralNetworkTests.c b/neuralNetworkTests.c index 21ab370..9fb1e98 100644 --- a/neuralNetworkTests.c +++ b/neuralNetworkTests.c @@ -6,9 +6,56 @@ #include "neuralNetwork.h" -static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) +static void writeDimension(FILE *file, unsigned int value) { - // TODO + const int serializedValue = (int)value; + + TEST_ASSERT_EQUAL_size_t(1, fwrite(&serializedValue, sizeof(serializedValue), 1, file)); +} + +static void writeMatrix(FILE *file, const Matrix matrix) // writes all matrix elements in order +{ + const size_t elementCount = matrix.rows * matrix.cols; + + TEST_ASSERT_EQUAL_size_t(elementCount, fwrite(matrix.buffer, sizeof(MatrixType), elementCount, file)); +} + +static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork model) +{ + FILE *file = fopen(path, "wb"); + TEST_ASSERT_NOT_NULL(file); + + //writes header + const size_t headerLen = strlen(NEURAL_NETWORK_FILE_HEADER); + TEST_ASSERT_EQUAL_size_t(headerLen, fwrite(NEURAL_NETWORK_FILE_HEADER, sizeof(char), headerLen, file)); + + if(model.numberOfLayers == 0) + { + // sends 0 to loadModel so it terminates + writeDimension(file, 0); + writeDimension(file, 0); + fclose(file); + return; + } + + // writes first layer + writeDimension(file, model.layers[0].weights.cols); + writeDimension(file, model.layers[0].weights.rows); + + for(unsigned int layerCount = 0; layerCount < model.numberOfLayers; layerCount++) // write all other layers + { + const Layer layer = model.layers[layerCount]; + + writeMatrix(file, layer.weights); + writeMatrix(file, layer.biases); + + const unsigned int nextOutput = (layerCount + 1 < model.numberOfLayers) //checks if there is another layer + ? model.layers[layerCount + 1].weights.rows + : 0; + writeDimension(file, nextOutput); // if 0 recieved loadModel() will terminate + } + + fclose(file); } void test_loadModelReturnsCorrectNumberOfLayers(void)