0

I've started using the Deep Java Library together with its underlying array manipulation package: ndarray.

The question is very simple. I want to modify the i-th element of an existing NDArray, however I cannot do that. How can I set the i-th element to a specific value?

The documentation mentions many set methods.

Here's a minimum reproducible example of what I've tried:

var manager = NDManager.newBaseManager();

var y = manager.create(new float[] {1, 2, 3, 4, 5});
System.out.println("y before modification: " + y);

y.set(new float[] {1, 100, 3, 4, 5});
System.out.println("y after setting the entire array: " + y);

// the following throws: "java.lang.UnsupportedOperationException: Tensor cannot be modified after creation"
y.set(new NDIndex("1"), 1000f);
System.out.println("y after setting the 1st element to 1000: " + y);

This the error thrown:

java.lang.UnsupportedOperationException: Tensor cannot be modified after creation

waykiki
  • 914
  • 2
  • 9
  • 19

1 Answers1

0

The exception you got is because you are using TensorFlow engine. The TensorFlow engine doesn't support modification of NDArray after creation.

You can choose PyTorch engine. Your code should just work. You only need to replace your tensorflow dependency with pytorch in your project. If you have multiple engines in your classpath, you can explicitly select PyTorch:

var manager = NDManager.newBaseManager(Device.cpu(), "PyTorch");

Frank Liu
  • 281
  • 1
  • 4
  • Thanks for the info, that makes sense. I do have a follow-up question though. I'm using a tensorflow model and want to do some preprocessing before inference. If I process arrays using PyTorch as an engine can I feed those arrays to a tensorflow model? – waykiki Dec 17 '22 at 11:11
  • You can use PyTorch to update the NDArray and convert it back to TensorFlow. But it won't be efficient. You can still do most of TensorFlow NDArray operations (except set/get using NDIndex). What you can do is get the ByteBuffer from the NDArray, and manipulate the Buffer in Java, the create new TfNDArray, or set Buffer back. – Frank Liu Dec 18 '22 at 16:32