C. Beck
C. Beck

Reputation: 13

Result of matrix-multiplication is 'nan'

Here I have a two matrix-multiplications in my code. The first one works fine but the second one gives me 'nan' outputs.

Sigmoide:

double sigmoide(double value) {
    return 1.0 / (1.0 + exp(-value));
}

Initialize:

double LO = -0.5;
double HI = 0.5;

double input[50][2];                          
double hiddenWeights[2][10];                   
double outputWeights[11][1];                  
double hiddenResults[50][11];                  
double outputResults[50][1];                                     

for (int i = 0; i < 50; i++) {
    input[i][0] = 1.0f;                       /// Bias
    input[i][1] = (7.0f/50.0f) * (double)i;   /// Samples
}

for (int i = 0; i < 50; i++) {
    outputSetpoint[i][0] = sin((7.0f/50.0f) * (double)i);
}

Random values between -0.5 and 0.5:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 10; j++) {
        hiddenWeights[i][j] = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));   
    }
}

for (int i = 0; i < 11; i++) {
    for (int j = 0; j < 1; j++) {
        outputWeights[i][j] = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO))); 
    }
}

Matrix-multiplication:

for (int s = 0; s < 50; s++) {
    for (int j = 0; j < 10; j++) {
        for (int i = 0; i < 2; i++) {
            // First matrix-multiplication
            hiddenResults[s][j] += nexttowardf(input[s][i] * hiddenWeights[i][j], 0.0f);            
        }
        hiddenResults[s][10] = 1.0f;                                               
        hiddenResults[s][j] = sigmoide(hiddenResults[s][j]);                      
    }

    for (int j = 0; j < 1; j++) {
        for (int i = 0; i < 11; i++) {
            // Second matrix-multiplication
            outputResults[s][j] += hiddenResults[s][i] * outputWeights[i][j];   
        }                                                                           
        outputResults[s][j] = sigmoide(outputResults[s][j]);                    
        error = outputSetpoint[s][j] - outputResults[s][j];
    }

    std::cout << outputResults[s][0] << std::endl;
}

Output:

nan
1
0.287491
0.432262
0.293168
0.336324
0.283587
0.282668
1
0.333261
nan
0.279217
nan
0.239026
0
0.338551
0.274522
0.209411
0.24247
0.273364
0.179109
0.199499
0.271506
1
nan
nan
nan
nan

Upvotes: 1

Views: 1033

Answers (1)

molbdnilo
molbdnilo

Reputation: 66441

You forgot to initialise hiddenResults and outputResults

Do it:

double hiddenResults[50][11] = {0};
double outputResults[50][1] = {0};

Initialise the other variables while you're at it.
It's a good habit to get into.

Upvotes: 1

Related Questions