【发布时间】:2019-02-14 21:31:07
【问题描述】:
我正在分析我的代码,这一行似乎是一个瓶颈。这个想法是基于相同维度的θ向量创建给定维度的n个观测值的空间相关矩阵 - 其中包含要拟合的维度超参数。
在我的整体代码中,在计算似然函数以优化我的 theta 参数时,这个空间相关函数被调用了数千次(每次迭代)。在整个代码的每次迭代中,观察的数量都会增加一个,并且每次迭代都必须重新拟合 theta 参数。因此,您可以看到随着算法的进展,这行代码如何变得至关重要。
我认为最慢的线,即R = exp(sum(bsxfun(@times, -abs(D_X).^corr_model,reshape(theta,[1 1 d])),3)); 花费最多的时间来计算最终的 n × n 矩阵的最终元素指数(n × n 矩阵是在对 3 维求和后产生的)距离矩阵)。但是这条线有很多事情要做,所以我不确定这是否是整体性能最关键的方面。
感谢您提供的任何见解!
我已经用bsxfun 替换了repmat 命令,以将给定的thetas 乘以维度距离矩阵D_X,这显着加快了代码速度。但是,嵌套第二个bsxfun 来执行距离平方,即替换abs(D_X).^corr_model,会使代码运行速度变慢。
n = 500;
dimension = 20;
D_X = repmat(rand(n),[1 1 dimension]);
theta = rand(dimension, 1);
corr_model = 2;
R = corr(corr_model,theta, D_X);
function R = corr(corr_model,theta,D_X)
% calculate the correlation matrix for the modified nugget effect model
% corr_model - the correlation model used for the spatial correlation
% corr_model = 2: gaussian correlation function
% theta - vector of hyperparameters
% D_X - the distance matrix for the input locations
d = size(theta,1);
switch corr_model
case 2 %Gaussian correlation function
R = exp(sum(bsxfun(@times, -abs(D_X).^corr_model,reshape(theta,[1 1 d])),3));
end
end
【问题讨论】:
标签: matlab performance