【问题标题】:Very slow execution of user defined convolution function for neural network in MATLAB在MATLAB中为神经网络执行用户定义的卷积函数非常慢
【发布时间】:2018-08-25 22:54:19
【问题描述】:

我在 MATLAB 中实现了卷积神经网络(来自开源 DeepLearnToolbox)。以下代码求不同权重和参数的卷积:

 z = z + convn(net.layers{l - 1}.a{i}, net.layers{l}.k{i}{j}, 'valid');

为了更新工具,我使用以下代码实现了自己的基于定点方案的卷积:

function result = convolution(image, kernal)

% find dimensions of output
row = size(image,1) - size(kernal,1) + 1;
col = size(image,2) - size(kernal,2) + 1;
zdim = size(image,3);

%create output matrix
output = zeros(row, col);

% flip the kernal
kernal_flipped = fliplr(flipud(kernal));

%find rows and col of kernal for loop iteration
row_ker = size(kernal_flipped,1);
col_ker = size(kernal_flipped,2);

for k = 1 : zdim
    for i = 0 : row-1
        for j = 0 : col-1
            sum = fi(0,1,8,7);
             prod = fi(0,1,8,7);
            for k_row = 1 : row_ker
                for k_col = 1 : col_ker
                    a = image(k_row+i, k_col+j, k);
                    b = kernal_flipped(k_row,k_col);
                    prod = a * b;
                   % convert to fixed point                     
                    prod = fi((product/16384), 1, 8, 7);

                    sum = fi((sum + prod), 1, 8, 7);
                end
            end
            output(i+1, j+1, k) = sum;
        end
    end
end

result = output;
end

问题是当我在更大的应用程序中使用我的卷积实现时,它非常慢。 有什么建议可以提高它的执行时间吗?

【问题讨论】:

  • 使用 MATLAB 的 conv2 函数。你写不出比这更快的东西了。
  • @CrisLuengo:默认实现已经使用“convn”函数。我想用我自己的卷积实现来替换它。
  • 要了解它是如何工作的?还是你有其他原因?您无法在 MATLAB 中编写快速卷积,即使您自己使用 C 之类的编译语言编写,它仍然会比 conv2 慢。

标签: matlab deep-learning conv-neural-network convolution fixed-point


【解决方案1】:

MATLAB 不支持定点 2D 卷积,但知道卷积可以写成矩阵乘法并且 MATLAB 支持fixed point matrix multiplication,您可以使用im2col 将图像转换为列格式并乘以内核对它们进行卷积。

row = size(image,1) - size(kernal,1) + 1;
col = size(image,2) - size(kernal,2) + 1;
zdim = size(image,3);

output = zeros(row, col);

kernal_flipped = fliplr(flipud(kernal));

fi_kernel = fi(kernal_flipped(:).', 1, 8, 7) / 16384;   

sz = size(kernal_flipped);
sz_img = size(image);

% Use the generated indexes to convert the image into column format
idx_col = im2col(reshape(1:numel(image)/zdim,sz_img(1:2)),sz,'sliding');
image = reshape(image,[],zdim);

for k = 1:zdim
    output(:,:,k) = double(fi_kernel * reshape(image(idx_col,k),size(idx_col)));
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2018-07-25
    • 1970-01-01
    • 2021-03-30
    相关资源
    最近更新 更多