矩阵乘法的结果是 'nan'

Result of matrix-multiplication is 'nan'

我的代码中有两个矩阵乘法。第一个工作正常,但第二个给了我 'nan' 输出。

乙状结肠:

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

初始化:

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);
}

-0.5 到 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))); 
    }
}

矩阵乘法:

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;
}

输出:

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

您忘记初始化 hiddenResultsoutputResults

这样做:

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

一边初始化其他变量。
养成好习惯。