MXNet (1) nd 的操作

談深度學習框架前通常會先看看各框架定義 tensor 的方法。

MXNet 的 nd module 提供了一系列類似 numpy 和 PyTorch 的操作方式。


1. 建立一個 nd array:

我們可以把一個 list 轉成 nd arrray 的形式:

from mxnet import nd

a = nd.array([[1,2,3],[4,5,6]])
print("a: ", a)

執行結果如下:

a:  
[[1. 2. 3.]
 [4. 5. 6.]]
<NDArray 2x3 @cpu(0)>

上面我們實例化了一個名為 a 的 nd array,shape為 [2,3]。特別需要注意的是 a 是一個 cpu 上的 nd array。


2. 其他常用的 functions:

ones 和 full 是滿常用的 functions,用來建立相同元素的 nd array。

b = nd.ones((2,2))
c = nd.full((3,3), 10.0)

3. slice

我們可以從 nd array 選取我們需要的範圍。

d = nd.ones((10,10))
e = d[0:2, 0:2]
print("d[0:2, 0:2]:", e)

4. 轉成 numpy:

以 CV 而言我們常需要把圖片 tensor 轉回 numpy,才能顯示。

asnumpy() 提供我們一個轉換的橋樑:

f = e.asnumpy()
print("f: ", f)
print("type(f):", type(f))

5. 使用 GPU

假如你想把 nd array 放到 GPU 上就要用到 as_in_context()。

as_in_context() 會設定 nd array 的 context。

from mxnet import gpu

ctx = gpu(0)
g = e.as_in_context(ctx)
print("g: ", g)

留言

熱門文章