在使用Julia实现ML的过程中,我想创建一个空数组,该数组采用W矩阵,因此所有W都用于on表示法和索引
类似于W[1]
上的第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]
答案 0 :(得分:4)
真正的解决方案是使用push!
而不是append!
。
如果您在REPL中寻求帮助(按?
),则可以查看push!
的文档:
help?> push!
search: push! pushfirst! pushdisplay
push!(collection, items...) -> collection
Insert one or more items at the end of collection.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> push!([1, 2, 3], 4, 5, 6)
6-element Array{Int64,1}:
1
2
3
4
5
6
Use append! to add all the elements of another collection to collection. The result of the preceding example is
equivalent to append!([1, 2, 3], [4, 5, 6]).
答案 1 :(得分:3)
正确的方法是简单地使用 "Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"codeformation.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}```
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!
,这样在CPU上稳定阵列大小时速度会更快(除非您使用GPU)。