matrix.c aenderungen

This commit is contained in:
Kristin 2025-12-02 09:13:35 +01:00
parent 3c4e4df496
commit 2a1ff310db
12 changed files with 66 additions and 148 deletions

5
.gitignore vendored
View File

@ -2,6 +2,9 @@ mnist
runTests runTests
*.o *.o
*.exe *.exe
.vscode/c_cpp_properties.json .vscode/settings.json
.vscode/launch.json .vscode/launch.json
.vscode/settings.json .vscode/settings.json
.vscode/settings.json
runImageInputTests
testFile.info2

View File

@ -1,18 +0,0 @@
{
"configurations": [
{
"name": "windows-gcc-x64",
"includePath": [
"${workspaceFolder}/**"
],
"compilerPath": "C:/ProgramData/mingw64/mingw64/bin/gcc.exe",
"cStandard": "${default}",
"cppStandard": "${default}",
"intelliSenseMode": "windows-gcc-x64",
"compilerArgs": [
""
]
}
],
"version": 4
}

24
.vscode/launch.json vendored
View File

@ -1,24 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "C/C++ Runner: Debug Session",
"type": "cppdbg",
"request": "launch",
"args": [],
"stopAtEntry": false,
"externalConsole": true,
"cwd": "c:/Users/Max-R/I2Pr/repoKachelto/I2-Pr_neuronalesNetz/info2Praktikum-NeuronalesNetz",
"program": "c:/Users/Max-R/I2Pr/repoKachelto/I2-Pr_neuronalesNetz/info2Praktikum-NeuronalesNetz/build/Debug/outDebug",
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}

58
.vscode/settings.json vendored
View File

@ -1,59 +1,3 @@
{ {
"C_Cpp_Runner.cCompilerPath": "gcc", "makefile.configureOnOpen": false
"C_Cpp_Runner.cppCompilerPath": "g++",
"C_Cpp_Runner.debuggerPath": "gdb",
"C_Cpp_Runner.cStandard": "",
"C_Cpp_Runner.cppStandard": "",
"C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat",
"C_Cpp_Runner.useMsvc": false,
"C_Cpp_Runner.warnings": [
"-Wall",
"-Wextra",
"-Wpedantic",
"-Wshadow",
"-Wformat=2",
"-Wcast-align",
"-Wconversion",
"-Wsign-conversion",
"-Wnull-dereference"
],
"C_Cpp_Runner.msvcWarnings": [
"/W4",
"/permissive-",
"/w14242",
"/w14287",
"/w14296",
"/w14311",
"/w14826",
"/w44062",
"/w44242",
"/w14905",
"/w14906",
"/w14263",
"/w44265",
"/w14928"
],
"C_Cpp_Runner.enableWarnings": true,
"C_Cpp_Runner.warningsAsError": false,
"C_Cpp_Runner.compilerArgs": [],
"C_Cpp_Runner.linkerArgs": [],
"C_Cpp_Runner.includePaths": [],
"C_Cpp_Runner.includeSearch": [
"*",
"**/*"
],
"C_Cpp_Runner.excludeSearch": [
"**/build",
"**/build/**",
"**/.*",
"**/.*/**",
"**/.vscode",
"**/.vscode/**"
],
"C_Cpp_Runner.useAddressSanitizer": false,
"C_Cpp_Runner.useUndefinedSanitizer": false,
"C_Cpp_Runner.useLeakSanitizer": false,
"C_Cpp_Runner.showCompilationTime": false,
"C_Cpp_Runner.useLinkTimeOptimization": false,
"C_Cpp_Runner.msvcSecureNoWarnings": false
} }

View File

@ -4,6 +4,8 @@
#include <string.h> #include <string.h>
#define FILE_HEADER_STRING "__info2_image_file_format__" #define FILE_HEADER_STRING "__info2_image_file_format__"
// define BUFFER 100
// 10x10 pixel
/* ---------------------------------------------------------- /* ----------------------------------------------------------
1. Header prüfen 1. Header prüfen
@ -40,14 +42,14 @@ static int readSingleImage(FILE *file, GrayScaleImage *img,
img->width = width; img->width = width;
img->height = height; img->height = height;
size_t numPixels = (size_t)width * (size_t)height; size_t numPixels = (size_t)width * (size_t)height; // anzahl an pixeln
img->buffer = malloc(numPixels); img->buffer = malloc(numPixels);
if (!img->buffer) if (!img->buffer)
return 0; return 0;
if (fread(img->buffer, 1, numPixels, file) != numPixels) { if (fread(img->buffer, 1, numPixels, file) != numPixels) {
free(img->buffer); free(img->buffer);
img->buffer = NULL; img->buffer = NULL; // fehler bei ungültiger eingabe
return 0; return 0;
} }
return 1; return 1;

View File

@ -126,19 +126,25 @@ void test_readImagesFailsOnWrongFileTag(void) {
remove(path); remove(path);
} }
void test_read_GrayScale_Pixel(void) { // Test
GrayScaleImageSeries *series = NULL;
void test_read_GrayScale_Pixel(
void) { // testet das einlesen eines graustufenbildes von readImages()
GrayScaleImageSeries *series = NULL; // enthält später das Bild
const char *path = "testFile.info2"; const char *path = "testFile.info2";
prepareImageFile(path, 8, 8, 1, 1); prepareImageFile(path, 8, 8, 1,
1); // Höhe x Breite in Pixel, Anzahl Bilder und Kategorie
series = readImages(path); series = readImages(path);
TEST_ASSERT_NOT_NULL(series); TEST_ASSERT_NOT_NULL(series); // Speicher reservieren
TEST_ASSERT_NOT_NULL(series->images); TEST_ASSERT_NOT_NULL(series->images); // Inhalt ist da
TEST_ASSERT_EQUAL_UINT(1, series->count); TEST_ASSERT_EQUAL_UINT(1, series->count); // Anzahl der Bilder stimmt
for (int i = 0; i < (8 * 8); i++) { for (int i = 0; i < (8 * 8); i++) {
TEST_ASSERT_EQUAL_UINT8((GrayScalePixelType)i, series->images[0].buffer[i]); TEST_ASSERT_EQUAL_UINT8(
(GrayScalePixelType)i,
series->images[0].buffer[i]); // alle Pixelwerte prüfen
} }
clearSeries(series); clearSeries(series);

View File

@ -59,8 +59,8 @@ imageInputTests: imageInput.o imageInputTests.c $(unityfolder)/unity.c
# -------------------------- # --------------------------
clean: clean:
ifeq ($(OS),Windows_NT) ifeq ($(OS),Windows_NT)
del /f *.o *.exe
else
rm -f *.o mnist runMatrixTests runNeuralNetworkTests runImageInputTests rm -f *.o mnist runMatrixTests runNeuralNetworkTests runImageInputTests
else
del /f *.o *.exe
endif endif

View File

@ -9,7 +9,7 @@
MatrixType *buffer; //Zeiger auf Speicherbereich Reihen*Spalten MatrixType *buffer; //Zeiger auf Speicherbereich Reihen*Spalten
} Matrix;*/ } Matrix;*/
Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix createMatrix(const unsigned int rows, const unsigned int cols) {
if (cols == 0 || rows == 0) { if (cols == 0 || rows == 0) {
Matrix errorMatrix = {0, 0, NULL}; Matrix errorMatrix = {0, 0, NULL};
return errorMatrix; return errorMatrix;
@ -42,9 +42,10 @@ void setMatrixAt(const MatrixType value, Matrix matrix,
// rowIdx * matrix.cols -> Beginn der Zeile colIdx ->Spalte // rowIdx * matrix.cols -> Beginn der Zeile colIdx ->Spalte
// innerhalb der Zeile // innerhalb der Zeile
} }
MatrixType getMatrixAt(const Matrix matrix, MatrixType
unsigned int rowIdx, // Kopie der Matrix wird übergeben getMatrixAt(const Matrix matrix,
unsigned int colIdx) { const unsigned int rowIdx, // Kopie der Matrix wird übergeben
const unsigned int colIdx) {
if (rowIdx >= matrix.rows || colIdx >= matrix.cols || if (rowIdx >= matrix.rows || colIdx >= matrix.cols ||
matrix.buffer == NULL) { // Speichergröße nicht überschreiten matrix.buffer == NULL) { // Speichergröße nicht überschreiten
return UNDEFINED_MATRIX_VALUE; return UNDEFINED_MATRIX_VALUE;
@ -54,7 +55,7 @@ MatrixType getMatrixAt(const Matrix matrix,
return value; return value;
} }
Matrix broadcastingCols(const Matrix matrix, const unsigned int cols) { Matrix broadCastCols(const Matrix matrix, const unsigned int cols) {
Matrix copy1 = createMatrix(matrix.rows, cols); Matrix copy1 = createMatrix(matrix.rows, cols);
for (int r = 0; r < matrix.rows; r++) { for (int r = 0; r < matrix.rows; r++) {
MatrixType valueMatrix1 = getMatrixAt(matrix, r, 0); MatrixType valueMatrix1 = getMatrixAt(matrix, r, 0);
@ -64,7 +65,7 @@ Matrix broadcastingCols(const Matrix matrix, const unsigned int cols) {
} }
return copy1; return copy1;
} }
Matrix broadcastingRows(const Matrix matrix, const unsigned int rows) { Matrix broadCastRows(const Matrix matrix, const unsigned int rows) {
Matrix copy1 = createMatrix(rows, matrix.cols); Matrix copy1 = createMatrix(rows, matrix.cols);
for (int c = 0; c < matrix.cols; c++) { for (int c = 0; c < matrix.cols; c++) {
MatrixType valueMatrix1 = getMatrixAt(matrix, 0, c); MatrixType valueMatrix1 = getMatrixAt(matrix, 0, c);
@ -104,7 +105,7 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) {
return result; return result;
} else if (rowsEqual == 1 && (cols1 == 1 || cols2 == 1)) { } else if (rowsEqual == 1 && (cols1 == 1 || cols2 == 1)) {
if (cols1 == 1) { // broadcasting von vektor 1 zu matrix 1, add if (cols1 == 1) { // broadcasting von vektor 1 zu matrix 1, add
Matrix newMatrix = broadcastingCols(matrix1, cols2); Matrix newMatrix = broadCastCols(matrix1, cols2);
// add // add
Matrix result = createMatrix(newMatrix.rows, newMatrix.cols); Matrix result = createMatrix(newMatrix.rows, newMatrix.cols);
if (result.buffer == NULL) { if (result.buffer == NULL) {
@ -118,9 +119,10 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) {
setMatrixAt(sum, result, i, j); setMatrixAt(sum, result, i, j);
} }
} }
clearMatrix(&newMatrix);
return result; return result;
} else { } else {
Matrix newMatrix2 = broadcastingCols(matrix2, cols1); Matrix newMatrix2 = broadCastCols(matrix2, cols1);
// add // add
Matrix result = createMatrix(newMatrix2.rows, newMatrix2.cols); Matrix result = createMatrix(newMatrix2.rows, newMatrix2.cols);
if (result.buffer == NULL) { if (result.buffer == NULL) {
@ -134,13 +136,14 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) {
setMatrixAt(sum, result, i, j); setMatrixAt(sum, result, i, j);
} }
} }
return result; return result;
} }
} }
else if ((rows1 == 1 || rows2 == 1) && colsEqual == 1) { else if ((rows1 == 1 || rows2 == 1) && colsEqual == 1) {
if (rows1 == 1) { if (rows1 == 1) {
Matrix newMatrix = broadcastingRows(matrix1, rows2); Matrix newMatrix = broadCastRows(matrix1, rows2);
// add // add
Matrix result = createMatrix(newMatrix.rows, newMatrix.cols); Matrix result = createMatrix(newMatrix.rows, newMatrix.cols);
if (result.buffer == NULL) { if (result.buffer == NULL) {
@ -156,7 +159,7 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) {
} }
return result; return result;
} else { } else {
Matrix newMatrix2 = broadcastingRows(matrix2, rows1); Matrix newMatrix2 = broadCastRows(matrix2, rows1);
// add // add
Matrix result = createMatrix(newMatrix2.rows, newMatrix2.cols); Matrix result = createMatrix(newMatrix2.rows, newMatrix2.cols);
if (result.buffer == NULL) { if (result.buffer == NULL) {
@ -170,6 +173,7 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) {
setMatrixAt(sum, result, i, j); setMatrixAt(sum, result, i, j);
} }
} }
clearMatrix(&newMatrix2);
return result; return result;
} }
} else { } else {

View File

@ -13,17 +13,15 @@ typedef struct {
} Matrix; } Matrix;
Matrix createMatrix(unsigned int rows, unsigned int cols); Matrix createMatrix(const unsigned int rows, const unsigned int cols);
void clearMatrix(Matrix *matrix); void clearMatrix(Matrix *matrix);
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, void setMatrixAt(const MatrixType value, Matrix matrix,
unsigned int colIdx); const unsigned int rowIdx, const unsigned int colIdx);
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, MatrixType getMatrixAt(const Matrix matrix, const unsigned int rowIdx,
unsigned int colIdx); const unsigned int colIdx);
Matrix broadCastCols(const Matrix matrix, const unsigned int rows, Matrix broadCastCols(const Matrix matrix, const unsigned int cols);
const unsigned int cols); Matrix broadCastRows(const Matrix matrix, const unsigned int rows);
Matrix broadCastRows(const Matrix matrix, const unsigned int rows,
const unsigned int cols);
Matrix add(const Matrix matrix1, const Matrix matrix2); Matrix add(const Matrix matrix1, const Matrix matrix2);
Matrix multiply(const Matrix matrix1, const Matrix matrix2); Matrix multiply(const Matrix matrix1, const Matrix matrix2);

View File

@ -28,7 +28,11 @@ Gewichte: bestimmen, wie stark ein Eingangssignal auf ein Neuron wirkt
Dimension: Form der Matrizen für einen Layer*/ Dimension: Form der Matrizen für einen Layer*/
// speichert NeuralNetwork nn in binäre Datei->erzeugt Dateiformat /* Gewichtsmatrix der Layer:
*/
// speichert NeuralNetwork nn in binäre Datei->später kann es wieder geöffnet
// werden
static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) { static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) {
FILE *fptr = fopen(path, "wb"); // Binärdatei zum Schreiben öffnen FILE *fptr = fopen(path, "wb"); // Binärdatei zum Schreiben öffnen
if (fptr == NULL) if (fptr == NULL)
@ -36,11 +40,12 @@ static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) {
// Header ist Erkennungsstring am Anfang der Datei, loadmodel erkennt // Header ist Erkennungsstring am Anfang der Datei, loadmodel erkennt
// Dateiformat // Dateiformat
const char header[] = const char header[] = "__info2_neural_network_file_format__"; // header string
"__info2_neural_network_file_format__"; // header vor jedem Layer fwrite(header, sizeof(char), strlen(header),
fwrite(header, sizeof(char), strlen(header), fptr); fptr); // der header wird am Anfang der Datei platziert
// Wenn es keine Layer gibt, 0 eintragen, LoadModel gibt 0 zurück // Wenn es keine Layer gibt, 0 eintragen, LoadModel erkennt, dass Datei leer
// ist
if (nn.numberOfLayers == 0) { if (nn.numberOfLayers == 0) {
int zero = 0; int zero = 0;
fwrite(&zero, sizeof(int), 1, fptr); fwrite(&zero, sizeof(int), 1, fptr);
@ -49,7 +54,7 @@ static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) {
} }
// Layer 0, inputDimension: Anzahl Input-Neuronen, outputDimension: Anzahl // Layer 0, inputDimension: Anzahl Input-Neuronen, outputDimension: Anzahl
// Output-Neuronen // Output-Neuronen wird in Datei eingefügt
int inputDim = (int)nn.layers[0].weights.cols; int inputDim = (int)nn.layers[0].weights.cols;
int outputDim = (int)nn.layers[0].weights.rows; int outputDim = (int)nn.layers[0].weights.rows;
fwrite(&inputDim, sizeof(int), 1, fptr); fwrite(&inputDim, sizeof(int), 1, fptr);
@ -59,38 +64,36 @@ static void prepareNeuralNetworkFile(const char *path, const NeuralNetwork nn) {
x 1). Zwischen Layern wird nur die nächste outputDimension (int) x 1). Zwischen Layern wird nur die nächste outputDimension (int)
geschrieben. */ geschrieben. */
for (int i = 0; i < nn.numberOfLayers; i++) { for (int i = 0; i < nn.numberOfLayers; i++) {
Layer layer = nn.layers[i]; Layer layer = nn.layers[i]; // kürzer, durch alle layer iterieren
int wrows = (int)layer.weights.rows; int wrows = (int)layer.weights.rows;
int wcols = (int)layer.weights.cols; int wcols = (int)layer.weights.cols;
int wcount = wrows * wcols; int wcount = wrows * wcols; // Anzahl Gewichtseinträge
int bcount = int bcount =
layer.biases.rows * layer.biases.cols; /* normalerweise rows * 1 */ layer.biases.rows * layer.biases.cols; // Anzahl der Bias-Einträge
/* Gewichte (MatrixType binär) */ /* Gewichte */
if (wcount > 0 && layer.weights.buffer != NULL) { if (wcount > 0 && layer.weights.buffer != NULL) {
fwrite(layer.weights.buffer, sizeof(MatrixType), (size_t)wcount, fptr); fwrite(layer.weights.buffer, sizeof(MatrixType), (size_t)wcount, fptr);
} } // Gewichte werden als Matrix gespeichert
/* Biases (MatrixType binär) */ /* Biases */
if (bcount > 0 && layer.biases.buffer != NULL) { if (bcount > 0 && layer.biases.buffer != NULL) {
fwrite(layer.biases.buffer, sizeof(MatrixType), (size_t)bcount, fptr); fwrite(layer.biases.buffer, sizeof(MatrixType), (size_t)bcount, fptr);
} } // Biases werden als Vektor gespeichert
/* Für die nächste Layer: falls vorhanden, schreibe deren outputDimension */ /* outputDimensionen der nächsten Layer */
if (i + 1 < nn.numberOfLayers) { if (i + 1 < nn.numberOfLayers) {
int nextOutput = (int)nn.layers[i + 1].weights.rows; int nextOutput = (int)nn.layers[i + 1].weights.rows;
fwrite(&nextOutput, sizeof(int), 1, fptr); fwrite(&nextOutput, sizeof(int), 1, fptr);
} else { } else {
/* Letzte Layer: wir können das Ende signalisieren, indem wir ein 0 // loadModel erkennt 0 als Ende der Datei
schreiben. loadModel liest dann outputDimension = 0 und beendet die
Schleife. */
int zero = 0; int zero = 0;
fwrite(&zero, sizeof(int), 1, fptr); fwrite(&zero, sizeof(int), 1, fptr);
} }
} }
fclose(fptr); fclose(fptr); // Datei schließen
} }
void test_loadModelReturnsCorrectNumberOfLayers(void) { void test_loadModelReturnsCorrectNumberOfLayers(void) {