You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2019/01/24 18:14:37 UTC

[GitHub] yzhliu commented on a change in pull request #12690: [MXNET-1000] get Ndarray real value and form it from a NDArray

yzhliu commented on a change in pull request #12690: [MXNET-1000] get Ndarray real value and form it from a NDArray
URL: https://github.com/apache/incubator-mxnet/pull/12690#discussion_r250720021
 
 

 ##########
 File path: scala-package/core/src/main/scala/org/apache/mxnet/NDArray.scala
 ##########
 @@ -509,6 +510,63 @@ object NDArray extends NDArrayBase {
     array(sourceArr, shape, null)
   }
 
+  /**
+    * Create a new NDArray based on the structure of source Array
+    * @param sourceArr Array[Array...Array[MX_PRIMITIVE_TYPE]...]
+    * @param ctx context like to pass in
+    * @return an NDArray with the same shape of the input
+    */
+  def toNDArray(sourceArr: Array[_], ctx : Context = null) : NDArray = {
+    val shape = ArrayBuffer[Int]()
+    shapeGetter(sourceArr, shape, 0)
+    val container = new Array[Any](shape.product)
+    arrayCombiner(sourceArr, container, 0, container.length - 1)
+    val finalArr = container(0) match {
+      case f: Float => array(container.map(_.asInstanceOf[Float]), Shape(shape), ctx)
+      case d: Double => array(container.map(_.asInstanceOf[Double]), Shape(shape), ctx)
+      case _ => throw new IllegalArgumentException(s"Unsupported type ${container(0).getClass}")
+    }
+    finalArr
+  }
+
+  private def shapeGetter(sourceArr : Any,
+                          shape : ArrayBuffer[Int], shapeIdx : Int) : Unit = {
+    sourceArr match {
+      case arr: Array[_] if MX_PRIMITIVES.isValidType(arr(0)) => {
+        val arrLength = arr.length
+        if (shape.length == shapeIdx) {
+          shape += arrLength
+        }
+        require(shape(shapeIdx) == arrLength, "Each Array should have equal length")
+      }
+      case arr: Array[_] => {
+        val arrLength = arr.length
+        if (shape.length == shapeIdx) {
+          shape += arrLength
+        }
+        require(shape(shapeIdx) == arrLength,
+          s"Each Array should have equal length, expected ${shape(shapeIdx)}, get $arrLength")
+        arr.foreach(ele => shapeGetter(ele, shape, shapeIdx + 1))
+      }
+      case _ => throw new IllegalArgumentException(s"Wrong type passed: ${sourceArr.getClass}")
+    }
+  }
+
+  private def arrayCombiner(sourceArr : Any, arr : Array[Any],
 
 Review comment:
   better named flattenArray

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services