我试图在一组点上使用多项式回归将它们映射到曲线。当我构建设计矩阵时,分配值似乎没有正确进行。构造的矩阵是3×n矩阵,其中n是点的数量,并且与设计矩阵一样,第一列应该全部为1(来自// HERE IS ASSIGNMENT
部分)。当我打印矩阵时,第一列充满了随机数,通常是infs和nans。如何定期分配?这会导致使用矩阵进行任何数学运算时出现进一步的问题,因为它充满了数字和infs。
以下代码是构建矩阵的地方。
for (auto it = lane_lines.begin(); it != lane_lines.end(); it++) {
vector<pair<Point, Point> > lines = *it;
// Remove random line clusters
if (lines.size() < 10) {
it = --lane_lines.erase(it);
continue;
}
Mat design(lines.size() * 2, 3, CV_64FC1);
Mat y_vec(lines.size() * 2, 1, CV_64FC1);
for (int i = 0; i < lines.size(); i += 2) {
// HERE IS ASSIGNMENT
design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2, 1) = lines[i].first.x;
design.at<double>(i * 2, 2) = pow(lines[i].first.x, 2);
design.at<double>(i * 2 + 1, 0) = 1.0;
design.at<double>(i * 2 + 1, 1) = lines[i].second.x;
design.at<double>(i * 2 + 1, 2) = pow(lines[i].second.x, 2);
y_vec.at<double>(i * 2, 0) = lines[i].first.y;
y_vec.at<double>(i * 2 + 1, 0) = lines[i].second.y;
}
// TODO: Deal with all the NaNs
cout << design << endl;
cout << design.t() * design << endl;
cout << "DET: " << determinant(design.t() * design) << endl << endl;
Mat std_poly = ((design.t() * design).inv() * design.t()) * y_vec;
double a = std_poly.at<double>(0, 2);
double b = std_poly.at<double>(0, 1);
double c = std_poly.at<double>(0, 0);
double h = -b / (2 * a == 0 ? numeric_limits<double>::min() : 2 * a);
double k = c - (a * pow(h, 2));
tuple<double, double, double, Point> curve(a, b, c, Point(h, k));
curves.push_back(curve);
}
编辑:对于不同的数据集,似乎随机出现问题。
答案 0 :(得分:2)
首先看一下你的代码:
for (int i = 0; i < lines.size(); i += 2) {
// HERE IS ASSIGNMENT
design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2, 1) = lines[i].first.x;
design.at<double>(i * 2, 2) = pow(lines[i].first.x, 2);
design.at<double>(i * 2 + 1, 0) = 1.0;
design.at<double>(i * 2 + 1, 1) = lines[i].second.x;
design.at<double>(i * 2 + 1, 2) = pow(lines[i].second.x, 2);
y_vec.at<double>(i * 2, 0) = lines[i].first.y;
y_vec.at<double>(i * 2 + 1, 0) = lines[i].second.y;
}
对于第一次迭代i=0
这两行
design.at<double>(i * 2, 0) = 1.0;
design.at<double>(i * 2 + 1, 0) = 1.0;
成为:
design.at<double>(0, 0) = 1.0;
design.at<double>(1, 0) = 1.0;
然后下一次迭代是i=2
,因为循环中有i+=2
所以上面的行变为:
design.at<double>(4, 0) = 1.0;
design.at<double>(5, 0) = 1.0;
我认为您应该将i+=2
更改为i++
以修复此行为。
NB 您的代码可能还有其他问题。