在使用Julia实现机器学习时,我希望创建一个空数组来存储W的矩阵,这样所有W都可以使用统一的符号和索引表示
例如,对于第一层使用W[1]
,对于第二层使用W[2]
,其中W的类型是Vector{Matrix{Float64}}
我尝试了以下方法
julia> W = Vector{Matrix{Float64}}()0-element Array{Array{Float64,2},1}julia> append!(W, randn(2,3))ERROR: MethodError: Cannot `convert` an object of type Float64 to an object of type Array{Float64,2}Closest candidates are: convert(::Type{T}, ::AbstractArray) where T<:Array at array.jl:490 convert(::Type{T}, ::T) where T<:AbstractArray at abstractarray.jl:14 convert(::Type{T}, ::LinearAlgebra.Factorization) where T<:AbstractArray at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/LinearAlgebra/src/factorization.jl:53
即使我尝试使用push!
,也返回了奇怪的结果
julia> push!(W, randn(2,3))7-element Array{Array{Float64,2},1}: #undef #undef #undef #undef #undef #undef [1.0062340094124418 -0.38626851094866743 -0.33618129619245823; 0.015522767526406687 0.28674191528121296 -1.0633951718710888]
回答:
正确的方法是简单地使用push!
julia> W = Vector{Matrix{Float64}}()0-element Array{Array{Float64,2},1}julia> push!(W, randn(2,3));julia> push!(W, randn(2,3))2-element Array{Array{Float64,2},1}: [0.3576168242438958 -1.317283838543733 1.2032446558953898; -0.23459653777447262 -1.0726558200371563 0.41327008176749974] [-0.09498247388794684 1.1652097582191079 0.33822625635995557; -0.12996397909088794 -1.1759095197792893 0.2507353185439138]
现在你可能会想“那些#undef
值是从哪里来的?”。当你尝试使用append!
时,它实际上扩展了你的W
的大小,增加了六个元素(你可以运行length(randn(2,3))
来自己查看)。这是因为append!
会遍历一个列表,当然也可以遍历矩阵。所以你可以观察到错误的副作用。
最后但同样重要的是,如果你的数组很小(这可能是你的情况),可以考虑使用StaticArrrays
,对于CPU上的稳定数组大小,它的速度要快得多(除非你在使用GPU)。