gpt4 book ai didi

c++ - Matrix Marginalization(边际分布)

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:24 26 4
gpt4 key购买 nike

我想对两个矩阵进行边缘化以获得第三个矩阵。基本上,我有两个大小为 (4x1) 的 Mat 对象,我想边缘化它们以获得行标准化的第三个 4 x 4 矩阵。这是通过将第一个 Mat 对象的第一行与第二个 Mat 对象的每一行相乘以填充第三个 4x4 Mat 的第一行来完成的,每个行元素乘法除以该行的总和,如下图所示.还有here .在下面找到我到目前为止采取的编码步骤并获得一些堆栈.... Diagrammatic illustration

const int nStates = 9;
register int iii, jjj;
float mMatrix[nStates][3] = {1,2,3,4,5,6,7,8,9};


//Pixelwise transitions
Mat nPot1 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat nPot2 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat NodeTransitions(nStates, nStates, CV_32FC1); NodeTransitions.setTo(Scalar(1.0f));
float fN1;
for( iii = 0; iii < nStates; iii++){
float * pPot1 = nPot1.ptr<float>(iii);
float * pPot2 = nPot2.ptr<float>(iii);
float * pNodeTrans = NodeTransitions.ptr<float>(iii);
//nPot1.at<float>(iii,0);
//nPot2.at<float>(iii,0);
float sum = 0;
for (int i =0; i < nStates; i++){
fN1 = pPot1[i]*pPot2[iii];
cout << fN1 << "\t";
}
for(jjj = 0; jjj < nStates; jjj++){
//pNodeTrans[jjj] = fN1;
}
//cout << endl;
}

谢谢。

最佳答案

只需计算外积,然后使用 L1 范数对每一行进行归一化。

我将把你的两个 vector 称为 xy。然后计算 R = x * y.t() 并沿每一行规范化 R

在 OpenCV 中有 Mat::dot函数,但它只为 vector 定义,你需要它为矩阵(当你转置你的输入之一,使其成为 1xn 矩阵或行 vector )。

这意味着,您必须手动完成。你也可以用 Eigen 做这些矩阵乘法.考虑一下,如果您进行大量矩阵乘法运算并且它们不代表图像等。

未经测试的代码:

const int nStates = 9;
float mMatrix[nStates][1] = {1,2,3,4,5,6,7,8,9};

//Pixelwise transitions
Mat nPot1 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat nPot2 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat NodeTransitions(nStates, nStates, CV_32FC1);
NodeTransitions.setTo(Scalar(1.0f)); // Why are you doing this?
float fN1;

// Pass one, compute outer product.
for (int row=0; row < nStates; row++) {
for (int col=0; col < nStates; col++) {
fN1 = nPot1.at<float>(row, 0) * nPot2.at<float>(col, 0);
NodeTransitions.at<float>(row, col) = fN1;
}
}

// Pass two, normalise each row.
for (int row=0; row < nStates; row++) {
// find sum of this row
fN1 = 0; // using fN1 for sum now.
for (int col=0; col < nStates; col++) {
fN1 += NodeTransitions.at<float>(row, col);
}
// Now divide all elements in row by sum
for (int col=0; col < nStates; col++) {
// divide value at row,col by fN1.
NodeTransitions.at<float>(row, col) /= fN1;
}
}

效率评价

鉴于您的 nStates 非常小,这段代码应该足够高效。看起来,您在尝试一次完成所有这些时遇到了困难。没有必要。

关于c++ - Matrix Marginalization(边际分布),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com