类型 Tensor 中最后一个参数的含义
在 Tensors.Tensor 中解释了如下的参数:
Tensor{order,dim,T<:Real}
Tensor type supported for
order ∈ (1,2,4)
anddim ∈ (1,2,3)
.
上面只解释了 3
个参数,在调用中会显示 Tensor
类型其实有 4
个参数
julia> Tensor{1,3,Float64}((1.0, 2.0, 3.0))
3-element Tensor{1,3,Float64,3}:
1.0
2.0
3.0
其中最后一个参数,表示了元素的个数
。
运算符 ⊗
Julia
中 Tensors.jl 有个很好玩的运算符 ⊗
(\otimes [tab]
)
julia> A = rand(SymmetricTensor{2, 2});
julia> B = rand(SymmetricTensor{2, 2});
julia> A ⊗ B
2×2×2×2 SymmetricTensor{4,2,Float64,9}:
[:, :, 1, 1] =
0.271839 0.352792
0.352792 0.260518
[:, :, 2, 1] =
0.469146 0.608857
0.608857 0.449607
[:, :, 1, 2] =
0.469146 0.608857
0.608857 0.449607
[:, :, 2, 2] =
0.504668 0.654957
0.654957 0.48365
Automatic Differentiation
目前还是不清楚怎么求一个函数的 gradient
,gradient
期望的是,下面我们想求一个简单的函数 f(x) = x^2
的导数在 xx
处的值,但是如下面几种情况 f1
直接就是错的:
julia> using Tensors
julia> xx = Vec{2}([3., 4.])
2-element Tensor{1,2,Float64,2}:
3.0
4.0
julia> f1(x) = x^2
f1 (generic function with 1 method)
julia> f2(x) = x[1]^2
f2 (generic function with 1 method)
julia> f3(x) = Vec{2}( (x[1]^2, x[2]^2) )
f3 (generic function with 1 method)
julia> g1 = gradient(f1,xx)
ERROR: MethodError: no method matching ^(::Tensor{1,2,ForwardDiff.Dual{Nothing,Float64,2},2}, ::Int64)
Closest candidates are:
^(::Float16, ::Integer) at math.jl:795
^(::Missing, ::Integer) at missing.jl:120
^(::Missing, ::Number) at missing.jl:93
...
Stacktrace:
[1] macro expansion at ./none:0 [inlined]
[2] literal_pow at ./none:0 [inlined]
[3] f1(::Tensor{1,2,ForwardDiff.Dual{Nothing,Float64,2},2}) at ./REPL[4]:1
[4] gradient(::typeof(f1), ::Tensor{1,2,Float64,2}) at /Users/yczhang/.julia/packages/Tensors/EOKLk/src/automatic_differentiation.jl:330
[5] top-level scope at none:0
julia> g2 = gradient(f2,xx)
2-element Tensor{1,2,Float64,2}:
6.0
0.0
julia> g3 = gradient(f3,xx)
2×2 Tensor{2,2,Float64,4}:
6.0 0.0
0.0 8.0