gpt4 book ai didi

Julia - 行外积的线性组合

转载 作者:行者123 更新时间:2023-12-04 16:35:53 27 4
gpt4 key购买 nike

我有一个 (n, m) 维度的矩阵 A(n, p) 维度的矩阵 B 。对于 n 行中的每一行,我想计算 A 行和 B 行之间的外积,它们是 (m, p) 矩阵。然后我有一个大小为 n 的向量 x 我想将这些矩阵中的每一个乘以 x 的相应条目并将所有内容相加.我该怎么做?

# Parameters
n, m, p = 100, 10, 3
# Matrices & Vectors
A, B, x = randn(n, m), randn(n, p), randn(n)
# Slow method
result = zeros(m, p)
for i in 1:n
result += x[i] * (A[i, :] * B[i, :]')
end

最佳答案

这是另一个版本

# Parameters
n, m, p = 100, 10, 3

# Matrices & Vectors
A, B, x = randn(n, m), randn(n, p), randn(n)

function old_way(A, B, x)
# Slow method
result = zeros(m, p)
for i in 1:n
result += x[i] * (A[i, :] * B[i, :]')
end
end

function another_way(A, B, x)
sum(xi * (Arow * Brow') for (xi, Arow, Brow) in zip(x, eachrow(A), eachrow(B)))
end

和基准测试:

julia> using BenchmarkTools

julia> @benchmark old_way(A, B, x)
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
Range (min … max): 83.495 μs … 2.653 ms ┊ GC (min … max): 0.00% … 95.79%
Time (median): 87.500 μs ┊ GC (median): 0.00%
Time (mean ± σ): 101.496 μs ± 115.196 μs ┊ GC (mean ± σ): 6.46% ± 5.53%

▃█▇▆▂ ▁ ▁ ▁ ▁
███████████████▇█▇██████▆▇▇▇▆▇▇▇▇▇▇▇▇▆▇▆▆▇▆▇▅▆▆▆▄▅▅▅▅▆▅▆▅▅▅▄▅ █
83.5 μs Histogram: log(frequency) by time 200 μs <

Memory estimate: 153.48 KiB, allocs estimate: 1802.


julia> @benchmark another_way(A, B, x)
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
Range (min … max): 25.850 μs … 923.032 μs ┊ GC (min … max): 0.00% … 95.94%
Time (median): 27.477 μs ┊ GC (median): 0.00%
Time (mean ± σ): 31.851 μs ± 35.440 μs ┊ GC (mean ± σ): 5.03% ± 4.49%

▇█▇▅▃▁ ▁▁▁ ▁
███████▇▇▆▇████████████▇█▇▇▇▆▇▆▅▆▆▆▅▆▆▅▆▆▇▆▅▅▅▆▅▆▅▅▅▄▃▅▅▅▄▄▄ █
25.8 μs Histogram: log(frequency) by time 77.4 μs <

Memory estimate: 98.31 KiB, allocs estimate: 304.

所以它更快一点,并且使用更少的内存。

这是否回答了您的问题?

关于Julia - 行外积的线性组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69942452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com