【问题标题】:Matlab Vectorization of Multivariate Gaussian Basis Functions多元高斯基函数的 Matlab 向量化
【发布时间】:2013-11-18 02:14:09
【问题描述】:

我有以下代码用于计算高斯函数的线性组合的结果。我真正想做的是以某种方式对其进行矢量化,以便它在 Matlab 中的性能更高。

注意y是列向量(输出),x是矩阵,其中每一列对应一个数据点,每一行对应一个维度(即2行=2D),variance是一个double,gaussians是一个矩阵其中每一列是对应于高斯平均点的向量,权重是每个高斯前面的权重的行向量。请注意,权重的长度比高斯大 1,因为 weights(1) 是 0 阶权重。

function [ y ] = CalcPrediction( gaussians, variance, weights, x )

basisFunctions = size(gaussians, 2);
xvalues = size(x, 2);
if length(weights) ~= basisFunctions + 1
    ME = MException('TRAIN:CALC', 'The number of weights should be equal to the number of basis functions plus one');
    throw(ME);
end


y = weights(1) * ones(xvalues, 1);

for xIdx = 1:xvalues
    for i = 1:basisFunctions
        diff = x(:, xIdx) - gaussians(:, i);
        y(xIdx) = y(xIdx) + weights(i+1) * exp(-(diff')*diff/(2*variance));
    end
end

end

您可以看到,目前我只是遍历 x 向量,然后遍历 2 个 for 循环中的高斯。我希望这可以得到改进 - 我看过 meshgrid 但这似乎只适用于向量(而且我有矩阵)

谢谢。

【问题讨论】:

  • 不能用mvnpdf吗?
  • @horchler 值得回答。

标签: matlab vectorization gaussian


【解决方案1】:

试试这个

diffx = bsxfun(@minus,x,permute(gaussians,[1,3,2])); % binary operation with singleton expansion
diffx2 = squeeze(sum(diffx.^2,1)); % dot product, shape is now [XVALUES,BASISFUNCTIONS]
weight_col = weights(:); % make sure weights is a column vector
y = exp(-diffx2/2/variance)*weight_col(2:end); % a column vector of length XVALUES

注意,我将 diff 更改为 diffx,因为 diff 是内置的。我不确定这会提高性能,因为分配数组会抵消矢量化的增加。

【讨论】:

  • 使用bsxfun 代替repmat 并使用向量矩阵乘积代替sum( a.*b )
  • 感谢 Mark,没有检查确切的改进,但在整个程序中它是相当可观的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2021-05-22
相关资源
最近更新 更多