matlab - 向量化回归图计算
问题描述
A(t)
我通过以下方式计算字段上时间序列的回归图B(x,y,t)
:
A=1:10; %time
B=rand(100,100,10); %x,y,time
rc=nan(size(B,1),size(B,2));
for ii=size(B,1)
for jj=1:size(B,2)
tmp = cov(A,squeeze(B(ii,jj,:))); %covariance matrix
rc(ii,jj) = tmp(1,2); %covariance A and B
end
end
rc = rc/var(A); %regression coefficient
有没有办法矢量化/加速代码?或者也许一些我不知道的内置函数可以达到相同的结果?
解决方案
为了向量化这个算法,你必须“弄脏你的手”并自己计算协方差。如果你看一下内部cov
,你会发现它有很多行输入检查和很少的实际计算行,总结一下关键步骤:
y = varargin{1};
x = x(:);
y = y(:);
x = [x y];
[m,~] = size(x);
denom = m - 1;
xc = x - sum(x,1)./m; % Remove mean
c = (xc' * xc) ./ denom;
为了稍微简化上述内容:
x = [x(:) y(:)];
m = size(x,1);
xc = x - sum(x,1)./m;
c = (xc' * xc) ./ (m - 1);
现在这是一个相当简单的矢量化...
function q51466884
A = 1:10; %time
B = rand(200,200,10); %x,y,time
%% Test Equivalence:
assert( norm(sol1-sol2) < 1E-10);
%% Benchmark:
disp([timeit(@sol1), timeit(@sol2)]);
%%
function rc = sol1()
rc=nan(size(B,1),size(B,2));
for ii=1:size(B,1)
for jj=1:size(B,2)
tmp = cov(A,squeeze(B(ii,jj,:))); %covariance matrix
rc(ii,jj) = tmp(1,2); %covariance A and B
end
end
rc = rc/var(A); %regression coefficient
end
function rC = sol2()
m = numel(A);
rB = reshape(B,[],10).'; % reshape
% Center:
cA = A(:) - sum(A)./m;
cB = rB - sum(rB,1)./m;
% Multiply:
rC = reshape( (cA.' * cB) ./ (m-1), size(B(:,:,1)) ) ./ var(A);
end
end
我得到了这些时间:[0.5381 0.0025]
这意味着我们在运行时节省了两个数量级:)
请注意,优化算法的很大一部分是假设您的数据中没有任何“奇怪”,例如NaN
值等。查看内部cov.m
以查看我们跳过的所有检查。
推荐阅读
- c++ - c++ 分配器特征引用和 const_reference 缺失以及迭代器到 const 迭代器的转换
- ios - 嵌入框架中的 @Fetched 请求 SwiftUI 和实体
- c# - 在 XAML Xamarin 表单中将属性绑定到 RelativeLayout.XConstraint
- python - 为什么在 Python 的 print 函数中传递给关键字参数 end 的参数在以下上下文中不能按预期工作?
- java - 在 Gradle clean 之后,Android Studio 没有清理依赖项
- c# - 如何按子字符串值对列表项进行排序?C#
- gdb - 为什么在为 Cortex-M 中断处理程序生成的程序集中存在死循环?
- javascript - 更改挂载中添加的新变量时,视图不会更新
- php - 如何翻译csv中的特殊字符
- php - docker php gettext没有翻译