MindSpore网络模型类
MindSpore網絡模型類
Q:使用MindSpore進行模型訓練時,CTCLoss的輸入參數有四個:inputs, labels_indices, labels_values, sequence_length,如何使用CTCLoss進行訓練?
A:定義的model.train接口里接收的dataset可以是多個數據組成,形如(data1, data2, data3, …),所以dataset是可以包含inputs,labels_indices,labels_values,sequence_length的信息的。只需要定義好相應形式的dataset,傳入model.train里就可以。具體的可以了解下相應的數據處理接口。
Q:模型轉移時如何把PyTorch的權重加載到MindSpore中?
A:首先輸入PyTorch的pth文件,以ResNet-18為例,MindSpore的網絡結構和PyTorch保持一致,轉完之后可直接加載進網絡,這邊參數只用到BN和Conv2D,若有其他層ms和PyTorch名稱不一致,需要同樣的修改名稱。
Q:模型已經訓練好,如何將模型的輸出結果保存為文本或者npy的格式?
A:網絡的輸出為Tensor,需要使用asnumpy()方法將Tensor轉換為numpy,再進行下一步保存。具體可參考:
out = net(x)
np.save(“output.npy”, out.asnumpy())
Q:使用MindSpore做分割訓練,必須將數據轉為MindRecords嗎?
A:build_seg_data.py是將數據集生成MindRecord的腳本,可以直接使用/適配數據集。或者如果想嘗試實現數據集的讀取,可以使用GeneratorDataset自定義數據集加載。
GenratorDataset 示例
GenratorDataset API說明
Q:MindSpore可以讀取TensorFlow的ckpt文件嗎?
A:MindSpore的ckpt和TensorFlow的ckpt格式是不通用的,雖然都是使用protobuf協議,但是proto的定義是不同的。當前MindSpore不支持讀取TensorFlow或PyTorch的ckpt文件。
Q:如何不將數據處理為MindRecord格式,直接進行訓練呢?
A:可以使用自定義的數據加載方式 GeneratorDataset,具體可以參考數據集加載文檔中的自定義數據集加載。
Q:MindSpore現支持直接讀取哪些其他框架的模型和哪些格式呢?比如PyTorch下訓練得到的pth模型可以加載到MindSpore框架下使用嗎?
A: MindSpore采用protbuf存儲訓練參數,無法直接讀取其他框架的模型。對于模型文件本質保存的就是參數和對應的值,可以用其他框架的API將參數讀取出來之后,拿到參數的鍵值對,然后再加載到MindSpore中使用。比如想用其他框架訓練好的ckpt文件,可以先把參數讀取出來,再調用MindSpore的save_checkpoint接口,就可以保存成MindSpore可以讀取的ckpt文件格式了。
Q:用MindSpore訓練出的模型如何在Ascend 310上使用?可以轉換成適用于HiLens Kit用的嗎?
A:Ascend 310需要運行專用的OM模型,先使用MindSpore導出ONNX或AIR模型,再轉化為Ascend 310支持的OM模型。具體可參考多平臺推理。可以,HiLens Kit是以Ascend 310為推理核心,所以前后兩個問題本質上是一樣的,需要轉換為OM模型.
Q:MindSpore如何進行參數(如dropout值)修改?
A:在構造網絡的時候可以通過 if self.training: x = dropput(x),驗證的時候,執行前設置network.set_train(mode_false),就可以不適用dropout,訓練時設置為True就可以使用dropout。
Q:從哪里可以查看MindSpore訓練及推理的樣例代碼或者教程?
A:可以訪問MindSpore官網教程訓練和MindSpore官網教程推理。
Q:MindSpore支持哪些模型的訓練?
A:MindSpore針對典型場景均有模型訓練支持,支持情況詳見Release note。
Q:MindSpore有哪些現成的推薦類或生成類網絡或模型可用?
A:目前正在開發Wide & Deep、DeepFM、NCF等推薦類模型,NLP領域已經支持Bert_NEZHA,正在開發MASS等模型,用戶可根據場景需要改造為生成類網絡,可以關注MindSpore Model Zoo。
Q:MindSpore模型訓練代碼能有多簡單?
A:除去網絡定義,MindSpore提供了Model類的接口,大多數場景只需幾行代碼就可完成模型訓練。
Q:如何使用MindSpore擬合f(x)=a×sin(x)+bf(x)=a×sin(x)+b這類函數?
A:以下擬合案例是基于MindSpore線性擬合官方案例改編而成。
# The fitting function is:f(x)=2*sin(x)+3.
import numpy as np
from mindspore import dataset as ds
from mindspore.common.initializer import Normal
from mindspore import nn, Model, context
from mindspore.train.callback import LossMonitor
context.set_context(mode=context.GRAPH_MODE, device_target=“CPU”)
def get_data(num, w=2.0, b=3.0):
# f(x)=w * sin(x) + b
# f(x)=2 * sin(x) +3
for i in range(num):
x = np.random.uniform(-np.pi, np.pi)
noise = np.random.normal(0, 1)
y = w * np.sin(x) + b + noise
yield np.array([np.sin(x)]).astype(np.float32), np.array([y]).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=[‘data’,‘label’])
input_data = input_data.batch(batch_size)
input_data = input_data.repeat(repeat_size)
return input_data
class LinearNet(nn.Cell):
def init(self):
super(LinearNet, self).init()
self.fc = nn.Dense(1, 1, Normal(0.02), Normal(0.02))
def construct(self, x):x = self.fc(x)return x
if name == “main”:
num_data = 1600
batch_size = 16
repeat_size = 1
lr = 0.005
momentum = 0.9
net = LinearNet()
net_loss = nn.loss.MSELoss()
opt = nn.Momentum(net.trainable_params(), lr, momentum)
model = Model(net, net_loss, opt)ds_train = create_dataset(num_data, batch_size=batch_size, repeat_size=repeat_size)model.train(1, ds_train, callbacks=LossMonitor(), dataset_sink_mode=False)print(net.trainable_params()[0], "\n%s" % net.trainable_params()[1])
Q:如何使用MindSpore擬合f(x)=ax2+bx+cf(x)=ax2+bx+c這類的二次函數?
A:以下代碼引用自MindSpore的官方教程的代碼倉
在以下幾處修改即可很好的擬合f(x)=ax2+bx+cf(x)=ax2+bx+c:
- 數據集生成。
- 擬合網絡。
- 優化器。
修改的詳細信息如下,附帶解釋。
# Since the selected optimizer does not support CPU, so the training computing platform is changed to GPU, which requires readers to install the corresponding GPU version of MindSpore.
context.set_context(mode=context.GRAPH_MODE, device_target=“GPU”)
# Assuming that the function to be fitted this time is f(x)=2x^2+3x+4, the data generation function is modified as follows:
def get_data(num, a=2.0, b=3.0 ,c = 4):
for i in range(num):
x = np.random.uniform(-10.0, 10.0)
noise = np.random.normal(0, 1)
# The y value is generated by the fitting target function ax^2+bx+c.
y = x * x * a + x * b + c + noise
# When ax^2+bx+c is fitted, a and b are weight parameters and c is offset parameter bias. The training data corresponding to the two weights are x^2 and x respectively, so the data set generation mode is changed as follows:
yield np.array([x*x, x]).astype(np.float32), np.array([y]).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=[‘data’,‘label’])
input_data = input_data.batch(batch_size)
input_data = input_data.repeat(repeat_size)
return input_data
class LinearNet(nn.Cell):
def init(self):
super(LinearNet, self).init()
# Because the full join function inputs two training parameters, the input value is changed to 2, the first Nomral(0.02) will automatically assign random weights to the input two parameters, and the second Normal is the random bias.
self.fc = nn.Dense(2, 1, Normal(0.02), Normal(0.02))
def construct(self, x):x = self.fc(x)return x
if name == “main”:
num_data = 1600
batch_size = 16
repeat_size = 1
lr = 0.005
momentum = 0.9
net = LinearNet()
net_loss = nn.loss.MSELoss()
# RMSProp optimalizer with better effect is selected for quadratic function fitting, Currently, Ascend and GPU computing platforms are supported.
opt = nn.RMSProp(net.trainable_params(), learning_rate=0.1)
model = Model(net, net_loss, opt)ds_train = create_dataset(num_data, batch_size=batch_size, repeat_size=repeat_size)
model.train(1, ds_train, callbacks=LossMonitor(), dataset_sink_mode=False)print(net.trainable_params()[0], "\n%s" % net.trainable_params()[1])
總結
以上是生活随笔為你收集整理的MindSpore网络模型类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MindSpore算子支持类
- 下一篇: MindSpore平台系统类