I am trying to use the Nd4J get and put methods to get and set sub sections of an array. However, it appears that the get method is returning a copy of the INDArray rather than a view of the array. It is my understanding that get is supposed to return a view of the same underlying array rather than a copy.
I created a simple Test class (shown below) to try to figure out why this is happening. The class has three INDArray array variables “array”, “arrayGet1”, “arrayGet2”, which I expect to all be pointing to the same underlying data (an array with a single value starting at 0), meaning that modifying any one of these arrays with put should change the value as seen through all 3 arrays. However, put only changes the particular array for which it is called suggesting that the arrays are actually copies of the original “array”.
Is there something that I’m doing wrong? Am I using get and put incorrectly?
package application;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.NDArrayIndex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test
{
private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) throws Exception
{
INDArray array = Nd4j.zeros(1);
INDArray arrayGet1 = array.get(NDArrayIndex.indices(0));
INDArray arrayGet2 = array.get(NDArrayIndex.indices(0));
LOGGER.info("a - array: {}, arrayGet1: {}, arrayGet2: {}", array, arrayGet1, arrayGet2);
arrayGet1.put(0, Nd4j.ones(1));
LOGGER.info("b - array: {}, arrayGet1: {}, arrayGet2: {}", array, arrayGet1, arrayGet2);
arrayGet2.put(0, Nd4j.ones(1).mul(2));
LOGGER.info("c - array: {}, arrayGet1: {}, arrayGet2: {}", array, arrayGet1, arrayGet2);
array.put(0, Nd4j.ones(1).mul(3));
LOGGER.info("d - array: {}, arrayGet1: {}, arrayGet2: {}", array, arrayGet1, arrayGet2);
}
}
Here is the output:
a.Test - a - array: [0], arrayGet1: [0], arrayGet2: [0]
a.Test - b - array: [0], arrayGet1: [1.0000], arrayGet2: [0]
a.Test - c - array: [0], arrayGet1: [1.0000], arrayGet2: [2.0000]
a.Test - d - array: [3.0000], arrayGet1: [1.0000], arrayGet2: [2.0000]
I would expect the output to be (all three variables point to the same underlying array data, 0, 1, 2, 3 in sequence):
a.Test - a - array: [0], arrayGet1: [0], arrayGet2: [0]
a.Test - b - array: [1.0000], arrayGet1: [1.0000], arrayGet2: [1.0000]
a.Test - c - array: [2.0000], arrayGet1: [2.0000], arrayGet2: [2.0000]
a.Test - d - array: [3.0000], arrayGet1: [3.0000], arrayGet2: [3.0000]