神经网络在OpenCV 3.0中只返回nan
Neural Network only returns NaNs in OpenCV 3.0
下面的代码显示了我用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)]
我做错了什么?
好的,解决了。激活函数需要显式设置。因此,在调用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]
相关文章:
- 为什么这段代码返回 -nan(ind)?C++
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- 有意返回 NaN
- 牛顿方法返回 NaN
- Double Exp(double)出乎意料地返回NAN(无浮子溢出)
- NAN通过指针访问时是否返回false
- AVX内在_mm256_cmp_ps是否应在为true时返回NaN
- OpenCV 3.1 ANN 预测返回 nan
- nan在C++中是什么意思?为什么pow(-4,-2.1)返回-nan
- 当 M 很大时返回 nan(ind)
- 特征库的矩阵逆函数返回NaN
- c++中返回NaN的函数
- 函数一直返回NaN
- 神经网络在OpenCV 3.0中只返回nan
- 为什么我的函数开始返回nan
- 返回NaN或抛出异常
- NaN或false作为双精度返回值
- 如果任一参数为 NaN,什么会导致 C/C++ <、<= 和 == 运算符返回 true?
- FFTW3 DFT 2D总是返回NaN
- 正态估计返回NAN的曲率场