首页 > 解决方案 > 将循环缓冲区重塑为第三维

问题描述

我们可以使用以下方法将常规矩阵重塑为第三维:

julia> data = rand(4,2)
4×2 Array{Float64,2}:
 0.89585   0.328315
 0.77878   0.619666
 0.232389  0.132091
 0.48543   0.829476

julia> reshape(data, 4, 1, 2)
4×1×2 Array{Float64,3}:
[:, :, 1] =
 0.895850499952602
 0.7787804133322247
 0.23238945917674037
 0.4854297310447009

[:, :, 2] =
 0.3283154491436233
 0.6196660556881552
 0.13209084702809903
 0.8294762758800456

但是如果使用 CircularBuffer 我们会得到一个错误:

using DataStructures

julia> data = CircularBuffer{Vector{Float64}}(4)
0-element CircularBuffer{Array{Float64,1}}

julia> push!(data, rand(2))
1-element CircularBuffer{Array{Float64,1}}:
 [0.0271144, 0.131345]

julia> push!(data, rand(2))
2-element CircularBuffer{Array{Float64,1}}:
 [0.0271144, 0.131345]
 [0.0483998, 0.384114]

julia> push!(data, rand(2))
3-element CircularBuffer{Array{Float64,1}}:
 [0.0271144, 0.131345]
 [0.0483998, 0.384114]
 [0.856657, 0.239313]

julia> push!(data, rand(2))
4-element CircularBuffer{Array{Float64,1}}:
 [0.0271144, 0.131345]
 [0.0483998, 0.384114]
 [0.856657, 0.239313]
 [0.573953, 0.0423042]

julia> reshape(data, 4, 1, 2)
ERROR: DimensionMismatch("parent has 4 elements, which is incompatible with size (4, 1, 2)")
Stacktrace:
 [1] _throw_dmrs(::Int64, ::String, ::Tuple{Int64,Int64,Int64}) at ./reshapedarray.jl:180
 [2] _reshape at ./reshapedarray.jl:175 [inlined]
 [3] reshape(::CircularBuffer{Array{Float64,1}}, ::Tuple{Int64,Int64,Int64}) at ./reshapedarray.jl:112
 [4] reshape(::CircularBuffer{Array{Float64,1}}, ::Int64, ::Int64, ::Vararg{Int64,N} where N) at ./reshapedarray.jl:115
 [5] top-level scope at none:0

标签: julia

解决方案


我猜你想要的是一个CircularArrayBuffer

julia> using ReinforcementLearningCore

julia> b = CircularArrayBuffer{Float64}(4, 2)
4×0 CircularArrayBuffer{Float64,2}

julia> push!(b, rand(4));

julia> push!(b, rand(4));

julia> reshape(b, 4, 1, 2)
4×1×2 reshape(::CircularArrayBuffer{Float64,2}, 4, 1, 2) with eltype Float64:
[:, :, 1] =
 0.09621058339946265
 0.19652636521722577
 0.14816367263437913
 0.5415815617368629

[:, :, 2] =
 0.38976815167466494
 0.9344752986999203
 0.43187275186834295
 0.7951761882018082

推荐阅读