技術背景

在深度學習或者其他引數優化領域中,對於結果的視覺化以及中間網路結構的視覺化,也是一個非常重要的工作。一個好的視覺化工具,可以更加直觀的展示計算結果,可以幫助人們更快的發掘大量的資料中最有用的資訊。而一般的深度學習框架或者是一些開源軟體會支援這種視覺化工具的介面。常見的視覺化工具有TensorBoard和MindSpore的MindInsight,本文主要介紹MindInsight的安裝與基本使用方法。

環境準備

MindInsight工具依賴於npm和nodejs,這裡我們用Ubuntu的包管理工具apt來直接安裝,首先需要更新apt的源和軟體:

(base) dechin@ubuntu2004:~/projects/gitee$ sudo apt update
獲取:1 file:/var/nccl-repo-2.7.6-ga-cuda11.0 InRelease
忽略:1 file:/var/nccl-repo-2.7.6-ga-cuda11.0 InRelease
獲取:2 file:/var/nccl-repo-2.7.6-ga-cuda11.0 Release [574 B]
獲取:2 file:/var/nccl-repo-2.7.6-ga-cuda11.0 Release [574 B]
命中:3 https://nvidia.github.io/libnvidia-container/stable/ubuntu18.04/amd64 InRelease
命中:4 https://nvidia.github.io/nvidia-container-runtime/stable/ubuntu18.04/amd64 InRelease
命中:5 https://nvidia.github.io/nvidia-docker/ubuntu18.04/amd64 InRelease
命中:6 http://dl.google.com/linux/chrome/deb stable InRelease
命中:8 http://repo.huaweicloud.com/ubuntu focal InRelease
命中:10 http://repo.huaweicloud.com/ubuntu focal-updates InRelease
命中:11 http://repo.huaweicloud.com/ubuntu focal-backports InRelease
命中:12 http://repo.huaweicloud.com/ubuntu focal-security InRelease
獲取:13 https://dl.cloudsmith.io/public/asbru-cm/release/deb/ubuntu focal InRelease [4,960 B]
忽略:9 https://developer.download.nvidia.cn/compute/machine-learning/repos/ubuntu1804/x86_64 InRelease
命中:14 https://developer.download.nvidia.cn/compute/machine-learning/repos/ubuntu1804/x86_64 Release
已下載 4,960 B,耗時 2秒 (2,625 B/s)
正在讀取軟體包列表... 完成
正在分析軟體包的依賴關係樹
正在讀取狀態資訊... 完成
有 13 個軟體包可以升級。請執行 ‘apt list --upgradable’ 來檢視它們。

然後就可以直接用apt install來安裝,這裡如果加上-y的選項,在軟體安裝的過程中就不需要再手動的輸入Y去確認是否要繼續安裝等:

(base) dechin@ubuntu2004:~/projects/gitee$ sudo apt install -y nodejs npm
正在讀取軟體包列表... 完成
正在分析軟體包的依賴關係樹
正在讀取狀態資訊... 完成
下列軟體包是自動安裝的並且現在不需要了:
linux-headers-5.8.0-50-generic linux-hwe-5.8-headers-5.8.0-50
linux-image-5.8.0-50-generic linux-modules-5.8.0-50-generic
linux-modules-extra-5.8.0-50-generic
使用'sudo apt autoremove'來解除安裝它(它們)。
將會同時安裝下列軟體:
...

安裝完成後可以用檢視版本號的指令驗證兩者是否被安裝成功:

(base) dechin@ubuntu2004:~/projects/gitlab/dechin/src/mindspore$ nodejs --version
v10.19.0
(base) dechin@ubuntu2004:~/projects/gitlab/dechin/src/mindspore$ npm --version
6.14.4

原始碼安裝MindInsight

首先從gitee倉庫下載原始碼:

git clone https://gitee.com/mindspore/mindinsight.git

然後進入目錄,使用pip遞迴的安裝requirements中所要求的依賴包:

(base) dechin@ubuntu2004:~/projects/gitee$ cd mindinsight/
(base) dechin@ubuntu2004:~/projects/gitee/mindinsight$ pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: Click>=7.0 in /home/dechin/.local/lib/python3.8/site-packages (from -r requirements.txt (line 1)) (8.0.1)
Requirement already satisfied: Flask>=1.1.1 in /home/dechin/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 2)) (1.1.2)
...
Successfully installed Flask-Cors-3.0.10 google-pasta-0.2.0 grpcio-1.36.0 gunicorn-20.1.0 marshmallow-3.12.1 treelib-1.6.1

最後在主目錄下使用python setup.py install的方式來安裝這個python庫:

(base) dechin@ubuntu2004:~/projects/gitee/mindinsight$ python3 setup.py install
running install
running build
running build_py
creating build/lib/mindinsight
copying mindinsight/__main__.py -> build/lib/mindinsight
copying mindinsight/__init__.py -> build/lib/mindinsight
copying mindinsight/_version.py -> build/lib/mindinsight
running egg_info
building ui ... > [email protected] postinstall /home/dechin/projects/gitee/mindinsight/mindinsight/ui/node_modules/babel-runtime/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

基本使用與案例演示

MindInsight與我們所常用的python庫有所不同,MindInsight更像是一種微服務,形式上與jupyter notebook有些類似。在使用前需要用mindinsight start來啟動服務,使用完成後,再使用mindinsight stop來關閉服務:

(base) dechin@ubuntu2004:~/projects/gitee/mindinsight$ mindinsight start
Workspace: /home/dechin/mindinsight
Summary base dir: /home/dechin/projects/gitee/mindinsight
Web address: http://127.0.0.1:8080
service start state: success
(base) dechin@ubuntu2004:~/projects/gitee/mindinsight$ mindinsight stop
Stop mindinsight service successfully

這裡我們來看一個案例,使用的案例是之前一篇部落格中所用到的用線性神經網路擬合非線性函式的python程式碼:

# test_nonlinear.py

from mindspore import context
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
import numpy as np
from mindspore import dataset as ds
from mindspore import nn, Tensor, Model
import time
from mindspore.train.callback import Callback, LossMonitor, SummaryCollector def get_data(num, a=2.0, b=3.0):
for _ in range(num):
x = np.random.uniform(-1.0, 1.0)
noise = np.random.normal(0, 0.03)
z = a * x ** 2 + b + noise
# 返回資料的時候就返回資料的平方
yield np.array([x**2]).astype(np.float32), np.array([z]).astype(np.float32) def create_dataset(num_data, batch_size=16, repeat_size=1):
input_data = ds.GeneratorDataset(list(get_data(num_data)), column_names=['x','z'])
input_data = input_data.batch(batch_size)
input_data = input_data.repeat(repeat_size)
return input_data if __name__ == '__main__':
data_number = 1600 # 一共產生1600組資料
batch_number = 16 # 分為16組分別進行優化
repeat_number = 2 # 重複2次,可以取到更低的損失函式值 ds_train = create_dataset(data_number, batch_size=batch_number, repeat_size=repeat_number)
dict_datasets = next(ds_train.create_dict_iterator()) class LinearNet(nn.Cell):
def __init__(self):
super(LinearNet, self).__init__()
self.fc = nn.Dense(1, 1, 0.02, 0.02) def construct(self, x):
x = self.fc(x)
return x net = LinearNet()
model_params = net.trainable_params()
print ('Param Shape is: {}'.format(len(model_params)))
for net_param in net.trainable_params():
print(net_param, net_param.asnumpy())
net_loss = nn.loss.MSELoss() # 設定優化演算法,常用的是Momentum和ADAM
optim = nn.Momentum(net.trainable_params(), learning_rate=0.005, momentum=0.9)
model = Model(net, net_loss, optim) epoch = 1
# 設定每8個batch訓練完成後就播報一次,這裡一共播報25次
summary_collector = SummaryCollector(summary_dir='./summary_dir')
model.train(epoch, ds_train, callbacks=[LossMonitor(8), summary_collector], dataset_sink_mode=False) for net_param in net.trainable_params():
print(net_param, net_param.asnumpy())

因為要使用MindInsight來展示結果,我們所需要執行的更改,只需要增加一個SummaryCollector的callback即可。執行上述python程式碼之後,可以看到在summary_dir目錄下生成了兩個檔案:

dechin@ubuntu2004:~/projects/gitlab/dechin/src/mindspore$ ll summary_dir/
總用量 24
drwxrwxr-x 2 dechin dechin 4096 7月 6 10:48 ./
drwxrwxr-x 7 dechin dechin 4096 7月 6 10:47 ../
-r-------- 1 dechin dechin 319 7月 6 10:48 events.out.events.summary.1625539702.0.ubuntu2004_lineage
-r-------- 1 dechin dechin 10064 7月 6 10:48 events.out.events.summary.1625539702.0.ubuntu2004_MS

最後在瀏覽器中輸入http://127.0.0.1:8080即可開啟訓練資料的視覺化面板:



包含有中間訓練的Loss Function趨勢:



還有引數配置詳情等:

總結概要

視覺化可以說在所有的研究領域中都是要仔細斟酌的問題,一個好的視覺化工具不僅可以為工作的開展帶來極大的便捷,在一些特殊的場景下還可以輔助人們進行一些重要的決策。比如在物理學領域中,最開始尋找相變點的技巧其實也是依賴於實驗資料的視覺化來實現的。而在深度學習領域,視覺化模型、視覺化訓練過程、視覺化引數以及視覺化的總結,可以讓我們迅速的得到模型好壞的結論,這一點我們在本文中通過研究MindInsight的一些安裝與使用技巧來進行實現。

版權宣告

本文首發連結為:https://www.cnblogs.com/dechinphy/p/msinsight.html

作者ID:DechinPhy

更多原著文章請參考:https://www.cnblogs.com/dechinphy/

打賞專用連結:https://www.cnblogs.com/dechinphy/gallery/image/379634.html

騰訊雲專欄同步:https://cloud.tencent.com/developer/column/91958

參考連結

  1. https://www.cnblogs.com/dechinphy/p/nonlinear.html