【问题标题】:Neural Network only returns NaNs in OpenCV 3.0神经网络仅在 OpenCV 3.0 中返回 NaN
【发布时间】:2015-12-21 19:35:26
【问题描述】:

以下代码显示了我使用 OpenCV 3.0 使用虚假值训练和测试神经网络的最小示例:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

int main()
{
    using namespace std;
    using namespace cv;

    int inputLayerSize = 1;
    int outputLayerSize = 1;
    int numSamples = 2;
    vector<int> layerSizes = { inputLayerSize, outputLayerSize };
    Ptr<ml::ANN_MLP> nnPtr = ml::ANN_MLP::create();
    nnPtr->setLayerSizes( layerSizes );

    Mat samples( Size( inputLayerSize, numSamples ), CV_32F );
    samples.at<float>( Point( 0, 0 ) ) = 0.1f;
    samples.at<float>( Point( 0, 1 ) ) = 0.2f;
    Mat responses( Size( outputLayerSize, numSamples ), CV_32F );
    responses.at<float>( Point( 0, 0 ) ) = 0.2f;
    responses.at<float>( Point( 0, 1 ) ) = 0.4f;

    cout << "samples:\n" << samples << endl;
    cout << "\nresponses:\n" << responses << endl;

    if ( !nnPtr->train( samples, ml::ROW_SAMPLE, responses ) )
        return 1;
    cout << "\nweights[0]:\n" << nnPtr->getWeights( 0 ) << endl;
    cout << "\nweights[1]:\n" << nnPtr->getWeights( 1 ) << endl;
    cout << "\nweights[2]:\n" << nnPtr->getWeights( 2 ) << endl;
    cout << "\nweights[3]:\n" << nnPtr->getWeights( 3 ) << endl;

    Mat output;
    nnPtr->predict( samples, output );
    cout << "\noutput:\n" << output << endl;
}

但预测只返回 NaN 而不是实际值。这是输出:

samples:
[0.1;
 0.2]

responses:
[0.2;
 0.40000001]

weights[0]:
[19.99999970197678, -3]

weights[1]:
[0.05355758607590463;
 0.01063728662926916]

weights[2]:
[inf, -nan(ind)]

weights[3]:
[0, 0]

output:
[-nan(ind);
 -nan(ind)]

我做错了什么?

【问题讨论】:

    标签: c++ opencv neural-network opencv3.0


    【解决方案1】:

    好的,解决了。激活函数需要明确设置。因此,在调用setLayerSizes 的那一行之后,问题就消失了:

    nnPtr->setActivationFunction( cv::ml::ANN_MLP::SIGMOID_SYM );
    

    输出:

    samples:
    [0.1;
     0.2]
    
    responses:
    [0.2;
     0.40000001]
    
    weights[0]:
    [19.99999970197678, -3]
    
    weights[1]:
    [1.811227207835904;
     -0.0006127133707308392]
    
    weights[2]:
    [0.1052631594632801, 0.3000000044703484]
    
    weights[3]:
    [9.49999985843897, -2.85]
    
    output:
    [0.20249137;
     0.39745635]
    

    【讨论】:

    • 你能告诉我如何为我的数据决定参数吗?
    • 抱歉,没有。我仍然是神经网络的初学者,目前我通过反复试验来选择我的参数。 ;)
    猜你喜欢
    • 2020-10-24
    • 2016-04-05
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2014-03-26
    • 2020-07-01
    • 2019-01-27
    相关资源
    最近更新 更多