问题描述
我最近从numpy切换到ND4J,但是很难理解ND4J中的广播如何工作.
I recently switched from numpy to ND4J but had a hard time understanding how broadcasting in ND4J works.
说我有两个ndarray,a的形状为[3,2,4,5],b的形状为[2,4,5].我想逐个元素地将它们加起来并向每个a[i] for i = 0 to 2
广播b.在numpy中,可以简单地通过a + b
完成,而在ND4J中,a.add(b)
会引发异常.我尝试了a.add(b.broadcast(3))
,但还是没有运气.
Say I have two ndarray, a of shape [3,2,4,5] and b of shape [2,4,5]. I would like to element-wise add them up and broadcast b to each a[i] for i = 0 to 2
. In numpy it can simply be done via a + b
, while in ND4J a.add(b)
throws an exception. I tried a.add(b.broadcast(3))
but still no luck.
在ND4J中执行此操作的正确方法是什么?
What is the correct way of doing this in ND4J?
推荐答案
到目前为止,我发现的唯一方法如下
The only method I have found so far is as following
var a = Nd4j.createUninitialized(Array(3,2,4,4))
var b = Nd4j.createUninitialized(Array(2,4,4))
b = b.reshape(1,32)
b = b.broadcast(3,32)
b = b.reshape(3, 2, 4, 4)
a.add(b)
请告诉我是否有更好的方法
Please kindly let me know if there is a better way to do this
这篇关于在ND4J中使用广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!