|
| 1 | +package org.nd4j.examples; |
| 2 | + |
| 3 | +import org.nd4j.linalg.api.ndarray.INDArray; |
| 4 | +import org.nd4j.linalg.factory.Nd4j; |
| 5 | + |
| 6 | +import java.io.*; |
| 7 | +import java.util.Objects; |
| 8 | + |
| 9 | +/** |
| 10 | + * Nd4j provides serialization of INDArrays many formats. This example gives some examples for binary and text |
| 11 | + * serialization. |
| 12 | + */ |
| 13 | +public class Nd4jEx16_Serialization { |
| 14 | + |
| 15 | + public static void main(String[] args) throws IOException { |
| 16 | + ClassLoader loader = Nd4jEx16_Serialization.class.getClassLoader(); // used to read files from resources. |
| 17 | + |
| 18 | + // 1. binary format from stream. |
| 19 | + INDArray arrWrite = Nd4j.linspace(1,25,25).reshape(5,5); |
| 20 | + String pathname = "tmp.bin"; |
| 21 | + DataOutputStream sWrite = new DataOutputStream(new FileOutputStream(new File(pathname ))); |
| 22 | + Nd4j.write(arrWrite, sWrite); |
| 23 | + |
| 24 | + DataInputStream sRead = new DataInputStream(new FileInputStream(new File(pathname ))); |
| 25 | + INDArray arrRead = Nd4j.read(sRead); |
| 26 | + // We now have our test matrix in arrRead |
| 27 | + System.out.println("Read from binary format:" ); |
| 28 | + System.out.println(arrRead ); |
| 29 | + |
| 30 | + |
| 31 | + // 2. Read the numpy npy (and npz) formats: |
| 32 | + File file = new File( Objects.requireNonNull(loader.getResource("twentyfive.npy")).getFile()); |
| 33 | + |
| 34 | + INDArray x = Nd4j.createFromNpyFile(file); // Nd4j.createFromNpzFile for npz Numpy files. |
| 35 | + System.out.println(); |
| 36 | + System.out.println("Read from Numpy .npyformat:" ); |
| 37 | + System.out.println(x); |
| 38 | + |
| 39 | + |
| 40 | + // 3. binary format from file. |
| 41 | + file = new File(pathname); |
| 42 | + Nd4j.saveBinary(arrWrite, file); |
| 43 | + arrRead = Nd4j.readBinary(file ); |
| 44 | + System.out.println(); |
| 45 | + System.out.println("Read from Numpy .npyformat:" ); |
| 46 | + System.out.println(arrRead); |
| 47 | + |
| 48 | + |
| 49 | + // 4. read a csv file. |
| 50 | + file = new File( Objects.requireNonNull(loader.getResource("twentyfive.csv")).getFile()); |
| 51 | + String Filename = file.getAbsolutePath(); |
| 52 | + arrRead = Nd4j.readNumpy(Filename, ","); |
| 53 | + System.out.println(); |
| 54 | + System.out.println("Read from csv format:" ); |
| 55 | + System.out.println(arrRead); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments