我似乎无法复制这种numpy算法。我正在使用Julia,但想知道此代码的数学解释。似乎打破了我对线性代数的了解。
X = np.arange(-5, 5, 0.2).reshape(-1, 1)
X.shape ## (50, 1)
test = np.sum(X**2, 1).reshape(-1, 1) + np.sum(X**2, 1)
test.shape ## (50, 50)
在朱莉娅,我会写
X = reshape(collect(range(-5, stop=5, length=N)), :, 1);
size(X) ## (50, 1)
test = sum(X.^2, dims=2) + vec(sum(X.^2, dims=2));
size(test) ## (50, 1)
我试图考虑将两个向量相加后得出50x50矩阵的结果吗?我知道numpy在幕后使用了大量广播,但是对我来说这还不清楚。
numpy在这里做什么的数学符号或茱莉亚等价物是什么?
您正在做很多事情,这些事情确实掩盖了您的观点,我认为这涉及如何添加不同形状的数组。
蟒蛇:
In [21]: x = np.random.rand(5, 1)
In [22]: x.shape
Out[22]: (5, 1)
In [23]: y = np.random.rand(1, 4)
In [24]: y.shape
Out[24]: (1, 4)
In [25]: (x + y).shape
Out[25]: (5, 4)
朱莉娅:
julia> x = rand(5);
julia> y = rand(1, 4);
julia> x + y
ERROR: DimensionMismatch("dimensions must match")
julia> x .+ y
5×4 Array{Float64,2}:
1.95779 1.31897 1.23345 1.32423
1.78126 1.14244 1.05692 1.14771
1.08306 0.444243 0.35872 0.449509
1.69756 1.05874 0.97322 1.06401
1.18661 0.547789 0.462265 0.553054
julia> size(x .+ y)
(5, 4)
如您所知,Python默认情况下会广播数组,而Julia要求您使用点运算符专门要求它.
。
正是因为添加两个不同形状的数组没有意义,Julia默认不会广播。同样,与乘法不同,*
其.*
区别在于:
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> B = [4 5; 6 7]
2×2 Array{Int64,2}:
4 5
6 7
julia> A * B
2×2 Array{Int64,2}:
16 19
36 43
julia> A .* B
2×2 Array{Int64,2}:
4 10
18 28
普通的*
是矩阵乘法,而后者是元素级数组乘法。
另一个例子:
julia> A = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> b = [7, 8]
2-element Array{Int64,1}:
7
8
julia> A * b
ERROR: DimensionMismatch("matrix A has dimensions (2,3), vector B has length 2")
julia> A .* b
2×3 Array{Int64,2}:
7 14 21
32 40 48
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句