iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
1
自我挑戰組

深度學習所需入門知識--一位初學者的認知系列 第 10

用 mxnet 操作數值, ndarray 最基礎的資料結構

由 Gavin 拍板接受 Fields 使用 MxNet 來當作他進入深度學習與相關數學的入門。 直接從 Mxnet 官方的教學網站 The Straight Dope 開始學習,首先自己先從 git clone 程式碼

git clone https://github.com/zackchase/mxnet-the-straight-dope.git
cd mxnet-the-straight-dope/
conda env create -f environment.yml #以environment.yml裡面指示安裝的套件 建立 gluon 環境
source activate gluon
pip install -U pip
pip install notedown #支援 Markdown,暫時用不到,但是先前建立的 Jupyter Config需要
pip install jupyter_contrib_nbextensions #安裝Jupter Notebook code cell執行計時套件
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime
jupyter notebook #會自動抓前文所製作的 ~/.jupyter/jupyter_notebook_config.py 。如果還沒做,請參考 https://ithelp.ithome.com.tw/articles/10203673

以Browser 連上指定網址以後出現
https://ithelp.ithome.com.tw/upload/images/20181024/20105283EEtL212GW8.png

進入 chapter01_crashcourse 第一章後,點選 ndarray.ipynb

https://ithelp.ithome.com.tw/upload/images/20181024/201052834bnPBDiVVd.png

進入第一個課題,假設我們已經抓到訓練用的資料集,那如何將數據放進電腦記憶體來進一步做運算呢? mxnet 提供了 NDArray,熟悉 Numpy 的人可能可以猜出它也是置放多維陣列(比較潮的說法叫『張量』)的資料結構,但是它添加了諸如 GPU 甚至分散式雲計算,而且他會幫忙做梯度計算,是針對深度學習優化的。要使用它相當容易:

import mxnet as mx 
from mxnet import nd
mx.random.seed(1)
x = nd.zeros((3, 5))
print(x)

可以得到 3x5 都是0. 的2維張量

[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
<NDArray 3x5 @cpu(0)>

我們可以很輕易的對張量做運算:

y = nd.random_normal(0, 1, shape=(3, 5))
print('x + y =',x+y)
print('x/y =',x/y)
print('exp(y) =',nd.exp(y))
print('nd.dot(x, y.T) =',nd.dot(x, y.T))

與先前談過得 Tuple,List等資料結構,我們也可以對 ndarry做切片 Slice;而且可以用 reshape 改變其型態。這個在數值計算經常用到。

print('x[1:3] =',x[1:3])
print('x[1:2,1:3] =',x[1:2,1:3])
#我們可以改變切片部份的值
x[1:2,1:3] = 5.0
print('new x =', x)

#我們可以改變張量型態方便後續做運算
z=nd.random_normal(0, 1, shape=(3, 6))
print(z.reshape((2, 9)))

進行數值運算時,常遇到兩個變量的型態不同,這時候 Broadcast 機制很重要。舉例來說:

a = nd.arange(3).reshape((3, 1))
b = nd.arange(2).reshape((1, 2))
print('a =', a)  
print('b =', b)
print()
print('a+b broadcast:',a + b)

a 是 3x1的張量 ;b 是 1x2的張量, 兩者相加自動以broadcast變形(資料複製到新的維度)成 3x2的張量。這個雖然不需要用指令操作,在後續程式碼細細的推算每個變量的維度,經常可以察覺到其蹤跡。

a = 
[[0.]
 [1.]
 [2.]]
<NDArray 3x1 @cpu(0)>
b = 
[[0. 1.]]
<NDArray 1x2 @cpu(0)>

a+b broadcast: 
[[0. 1.]
 [1. 2.]
 [2. 3.]]
<NDArray 3x2 @cpu(0)>

備註:

專案緣起記錄在 【UP, Scrum 與 AI專案】


上一篇
Tensorflow, PyTorch, Mxnet ...
下一篇
安裝GPU 加速的 CUDA 驅動
系列文
深度學習所需入門知識--一位初學者的認知31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言