在使用Julia实现ML的过程中,我想创建一个空数组,该数组采用W的矩阵,因此所有W都用于on表示法和索引
就像第1层一样W[1]
,对于第2层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)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句