我有以下代码用于计算高斯函数的线性组合的结果。我真正想做的是以某种方式对其进行矢量化,以便它在Matlab中更具性能。
注意y是列向量(输出),x是矩阵,其中每列对应一个数据点,每行对应一个维度(即2行= 2D),方差是双精度,高斯是矩阵其中每列是对应于高斯平均点的向量,权重是每个高斯前面的权重的行向量。请注意,权重的长度比高斯的大1,因为权重(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里面的高斯循环。我希望这可以改进 - 我看过meshgrid,但似乎只适用于矢量(我有矩阵)
感谢。
答案 0 :(得分: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 是内置的。我不确定这会改善性能,因为分配数组会通过矢量化来抵消增加。