矩阵乘法的结果是' nan'

时间:2016-10-25 10:57:00

标签: c++ arrays nan matrix-multiplication

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

S型:

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

1 个答案:

答案 0 :(得分:1)

您忘记初始化hiddenResultsoutputResults

做到:

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

在您使用时初始化其他变量 这是一个很好的习惯。