解决的问题:
拟合优度(Goodness of Fit)是指回归直线对观测值的拟合程度,度量拟合优度的统计量是可决系数(亦称确定系数) R?。R最大值为
1。R%的值越接近1,说明回归直线对观测值的拟合程度越好,反之,R%值越小,说明回归直线对观测值的拟合程度越差.
这是网上的介绍,那么根据算法的公式
咱们实现自己的算法
如何实现:
1:拟合出自己的曲线方程式
y = a0 + a1*x + a2*x^2;
如下图:
具体这个函数的拟合方法,有相应的代码,可以点关注私信我,我使用opencv自带的函数
cv::solve
然后就是计算R Squared的值
代码块解析:
double calculateMean(QVector<double> &numbers)
{double sum = 0.0;int count = 0.0;for (double number : numbers){sum += number;++count;}// 返回平均值return sum / count;
}double calculateYValue(double xValue)
{double yValue = 0.0;yValue = a0 + (a1 * xValue) + (a2*xValue*xValue);return yValue;
}double calculateRfitValue(QVector<double> x, QVector<double> y)
{double yMean = calculateMean(y);double SSR = 0.0;double SSE = 0.0;double SST = 0.0;for(int i = 0; i < x.length(); ++i){SSR += pow((calculateYValue(x[i]) - yMean), 2);SSE += pow((y[i] - calculateYValue(x[i])), 2);}SST = SSR + SSE;return (1.0- SSE/SST);
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);QVector<double> myX = {29.82,29.62,29.42,29.21,29.01,28.8,28.59,28.38,28.17,27.97,27.76,27.55,27.34,27.13,26.92,26.71,26.5,26.3,26.09,25.88};QVector<double> myY = {133.2,135.2,137.12,139.2,141.2,142.3,143.5,144.2,144.9,145.3,143.6,145.8,144.6,143.4,142.0,140.2,138.7,136.2,133.7,130.4};qDebug() << "r2: " << calculateRfitValue(myX, myY);return a.exec();
}