I have a trained neural network for classification problems in Matlab. I want to use the trained weight and apply it in C. My output of the neural network gives me a vector of 7 (output2[i]
).
How can I use the same vec2ind function in Matlab which takes a matrix of vectors, each containing a single 1, and returns the indices of the ones, and stop as soon as it finds the 1?
I want to implement it in C languages.
I attached part of the code
Thank you
double sum = 0;
/// matrix multiplication
for (int i = 0; i < 29; i )
{
for (int k = 0; k < 2; k )
{
sum = inputs[k] * weights[i][k];
}
/// apply activation function
output[i] = tanh_func(sum biases[i]);
sum = 0;
}
/// output layer
for (int i = 0; i < 7; i )
{
for (int k = 0; k < 29; k )
{
sum = output[k] * weights2[i][k];
}
/// apply activation function
output2[i] = sigmoid(sum biases2[i]);
sum = 0;
}
CodePudding user response:
To get a better understanding you could use a triple pointer double*** tensor3d
initialize it with
tensor3d = malloc( dim0 * sizeof( double** ));
for( int i = 0; i < dim0; i )
{
tensor3d[i] = malloc( dim1 * sizeof( double* ));
for( int j = 0; j < dim1; j )
{
tensor3d[i][j] = malloc( dim2 * sizeof( double ));
}
}
if you have copied the matrix of vectors inside that 3dim-array you can do that
int indices[dim0][dim1];
for( int i = 0; i < dim0; i )
{
for( int j = 0; j < dim1; j )
{
for( int k = 0; k < dim2; k )
{
if( tensor3d[i][j][k] > 0.99 && tensor3d[i][j][k] < 1.01 )
{
indices[i][j] = k;
break;
}
}
}
}
but in real life you would use a 1 dim-array flattensor3d[]
and
tensor3d[i][j][k] == flattensor3d[i * dim0 * dim1 j * dim1 k]
CodePudding user response:
For writing just vec2ind in C, see other answers.
Alternatively, if you have access to MATLAB Coder, that can convert MATLAB code (the entire algorithm) to C code automatically: https://www.mathworks.com/help/coder/index.html