1
INDArray image = loader.asMatrix(file);

How to convert INDArray to Json String and from Json String to INDArray. I searched in google it is not showing any results recording this.

Murali krishna
  • 823
  • 1
  • 8
  • 23
  • I assume an INDArray is a matrix, what type of data do you have inside ? Could you provide an example. Also are you able to transform it into a Java 2D array? – Bentaye Feb 16 '18 at 09:50

3 Answers3

3

Fiddling around I see that INDArray has a data() method (See INDArray API)

This gives you a DataBuffer which in turn has methods to export it as a Java array (See DataBuffer API)

So I reckon you should these and do:

INDArray image = loader.asMatrix(file);
DataBuffer dataBuffer = image.data();
int[] array = dataBuffer.asInt(); // or any type you want

Now you have a Java array, you can use Gson to make a Json String

Gson gson = new Gson();
String jsonString = gson.toJson(array);

I assume you can probably do the same in the other way (JSON to INDArray) Use Gson to transform your json string into java array then create an INDArray out of it. See user guide Creating NDArrays from Java arrays

Bentaye
  • 9,403
  • 5
  • 32
  • 45
1
    INDArray matrix=  imageLoader.asMatrix(file);

    System.out.println("INDArray Original: " + matrix);
    DataBuffer buff= matrix.data();
    double[] array= buff.asDouble();

    Gson gson= new Gson();
    String imageStr= gson.toJson(array);
    ArrayList<Double> result= gson.fromJson(imageStr, ArrayList.class);

    double[] r= ArrayUtil.toArrayDouble(result);

    int[] shape = matrix.shape();
    INDArray final_array= Nd4j.create(r, shape, 'c');
    System.out.println("After Java array to INDarray: " + final_array.toString());

Complete version of code to convert INDArray to Gson and from GSON to INDArray.

Murali krishna
  • 823
  • 1
  • 8
  • 23
0

for 2d array:

INDArray matrix = YOUR_MATRIX;
double[][] java2dArray = matrix.toDoubleMatrix();


INDArray matrix = ND4j.create(java2dArray);
kai
  • 1,640
  • 18
  • 11