ONNXParameters
Parameters of importedONNX深度学习网络
Description
ONNXParameters
包含导入ONNX™(开放神经网络交换)网络的参数(例如权重和偏置)。利用ONNXParameters
执行诸如转移学习之类的任务。
创建
创建一个ONNXParameters
目的通过使用experconnxfunction
。
Properties
可学习的
-网络培训期间更新的参数
结构体
在网络培训期间更新的参数,指定为结构。例如,卷积和完全连接的层的权重是网络在培训过程中学习的参数。阻止可学习的
参数更新培训期间,反对vert them toNonlearnables
通过使用冻结Parameters
。兑换frozen parameters back to可学习的
通过使用Unreezeparameters
。
Add a new parameter to参数。可学习的
通过使用addParameter
。Remove a parameter from参数。可学习的
通过使用删除参数
。
Access the fields of the structure可学习的
通过使用点符号。例如,参数。可学习的。conv1_W
可以显示第一卷积层的重量。通过输入来初始化转移学习的权重参数。可学习的。conv1_W = rand([1000,4096])
。有关分配新值和参数命名的更多详细信息,请参见Tips。
Nonlearnables
-网络培训期间没有变化的参数
结构体
在网络培训期间没有变化的参数指定为结构。例如,填充和大步是在训练过程中保持恒定的参数。
Add a new parameter to参数
通过使用addParameter
。Remove a parameter from参数
通过使用删除参数
。
Access the fields of the structureNonlearnables
通过使用点符号。例如,参数。conv1_Padding
could display the padding of the first convolution layer. For more details about parameter naming, seeTips。
状态
-Network state
结构体
网络状态,指定为结构。网络状态
包含迭代之间网络记住的信息,并在多个培训批次上进行更新。例如,LSTM和批处理层的状态为状态
参数。
Add a new parameter toparams.state
通过使用addParameter
。Remove a parameter fromparams.state
通过使用删除参数
。
Access the fields of the structure状态
通过使用点符号。例如,params.state。bn1_var
could display the variance of the first batch normalization layer. For more details about parameter naming, seeTips。
NumDimensions
-每个参数的尺寸数量
结构体
This property is read-only.
每个参数的尺寸数量,,,,specified as a structure.NumDimensions
包括尾随的单身尺寸。
Access the fields of the structureNumDimensions
通过使用点符号。例如,params.numdimensions.conv1_w
可以显示第一卷积层的权重参数的尺寸数。
NetworkFunctionName
-Name of model function
character vector|字符串标量
This property is read-only.
模型函数的名称,指定为字符向量或字符串标量。属性NetworkFunctionName
包含功能的名称NetworkFunctionName
,,,,which you specify inexperconnxfunction
。功能NetworkFunctionName
包含导入的ONNX网络的架构。
Example:'Shufflenetfcn'
对象功能
addParameter |
将参数添加到ONNXParameters 目的 |
冻结Parameters |
转换可学习的网络参数ONNXParameters 无法检测 |
删除参数 |
从中删除参数ONNXParameters 目的 |
Unreezeparameters |
兑换nonlearnable network parameters inONNXParameters to learnable |
Examples
使用自定义培训循环导入的火车在ONNX功能
导入squeezenet
卷积神经网络作为一个功能,并通过转移学习进行了验证的网络,以在新的图像集合中执行分类。
此示例使用多个辅助功能。要查看这些功能的代码,请参见Helper Functions。
解压缩并加载新图像作为图像数据存储。imageDatastore
自动根据文件夹名称标记图像,并将数据存储为一个成像
目的。图像数据存储使您能够存储大型图像数据,包括不适合内存的数据,并在卷积神经网络训练期间有效地读取图像的批次。指定迷你批量大小。
解压缩('MerchData.zip');minibatchsize = 8;imds = imagedatastore('merchdata',,,,...“包括橡皮folders”,真的,...“ Labelsource”,,,,“折叠式”,,,,...“读取尺寸”,minibatchSize);
This data set is small, containing 75 training images. Display some sample images.
numimages = numel(imds.labels);idx = randperm(numimages,16);数字为了i = 1:16 subplot(4,4,i) I = readimage(imds,idx(i)); imshow(I)结尾
Extract the training set and one-hot encode the categorical classification labels.
XTrain = readall(imds); XTrain = single(cat(4,XTrain{:})); YTrain_categ = categorical(imds.Labels); YTrain = onehotencode(YTrain_categ,2)';
确定数据中的类数。
class =类别(ytrain_categ);numClasses = numel(class)
数字= 5
squeezenet
is a convolutional neural network that is trained on more than a million images from the ImageNet database. As a result, the network has learned rich feature representations for a wide range of images. The network can classify images into 1000 object categories, such as keyboard, mouse, pencil, and many animals.
进口预处理squeezenet
网络作为函数。
squeezenetonnx()params = experconnxFunction('Squeezenet.onnx',,,,'squeezenetfcn')
包含导入ONNX网络的功能已保存到文件SqueezenetFcn.m。要了解如何使用此功能,请键入:帮助SqueezenetFCN。
参数= ONNXParameters with properties: Learnables: [1×1 struct] Nonlearnables: [1×1 struct] State: [1×1 struct] NumDimensions: [1×1 struct] NetworkFunctionName: 'squeezenetFcn'
参数
is anONNXParameters
包含网络参数的对象。挤压
is a model function that contains the network architecture.experconnxfunction
保存挤压
in the current folder.
Calculate the classification accuracy of the pretrained network on the new training set.
accuracyBeforeTraining = getNetworkAccuracy(XTrain,YTrain,params); fprintf('%.2f精度转移学习\ n',,,,accuracyBeforeTraining);
0.01 accuracy before transfer learning
准确性非常低。
通过键入显示网络的可学习参数参数。可学习的
。这些参数,例如权重(w
)和偏见(b
)在培训期间,网络更新了卷积和完全连接的层。在训练期间,非可检测的参数保持恒定。
这last two learnable parameters of the pretrained network are configured for 1000 classes.
conv10_w:[1×1×512×1000 dlarray]
conv10_b:[1000×1 dlarray]
参数conv10_w
和conv10_b
must be fine-tuned for the new classification problem. Transfer the parameters to classify five classes by initializing the parameters.
params.learnables.conv10_w = rand(1,1,512,5);params.learnables.conv10_b = rand(5,1);
冻结网络的所有参数,以将其转换为不可验证的参数。因为您不需要计算冷冻层的梯度,所以冻结许多初始层的重量可以显着加快网络训练。
参数= freezeParameters(params,'全部');
Unfreeze the last two parameters of the network to convert them to learnable parameters.
params = utreezeparameters(params,'conv10_w');params = utreezeparameters(params,'conv10_b');
现在,网络已经准备好培训了。初始化培训进度图。
情节=“训练过程”;如果绘图==“训练过程”数字lineLossTrain = animatedline; xlabel(“迭代”)ylabel(“失利”)结尾
指定培训选项。
速度= [];numEpochs = 5;miniBatchSize = 16;numObservations = size(YTrain,2); numIterationsPerEpoch = floor(numObservations./miniBatchSize); initialLearnRate = 0.01; momentum = 0.9; decay = 0.01;
训练网络。
iteration = 0; start = tic; executionEnvironment =“中央处理器”;%更改为“ GPU”以训练GPU。% Loop over epochs.为了epoch = 1:numepochs%洗牌数据。idx = randperm(numObservations);Xtrain = Xtrain(:,:,:,:,IDX);ytrain = ytrain(:,idx);% Loop over mini-batches.为了i = 1:NumiterationsPerePoch Iteration =迭代 + 1;% Read mini-batch of data.idx = (i-1)*miniBatchSize+1:i*miniBatchSize; X = XTrain(:,:,:,idx); Y = YTrain(:,idx);% If training on a GPU, then convert data to gpuArray.如果(executionEnvironment =="auto"&& canusegpu)||executionEnvironment ==“ GPU”x = gpuarray(x);结尾%使用DLFEVAL评估模型梯度和损失% modelGradients function.[渐变,损失,状态] = dlfeval(@modelGradients,x,y,params);params.state = state;% Determine the learning rate for the time-based decay learning rate schedule.learnRate = initialLearnRate/(1 + decay*iteration);% Update the network parameters using the SGDM optimizer.[params.learnables,速度] = sgdmupdate(params.learnables,渐变,速度);%显示培训进度。如果绘图==“训练过程”d =持续时间(0,0,toc(start),'Format',,,,'hh:mm:ss');addpoints(lineLossTrain,iteration,double(gather(extractdata(loss)))) title(“时代:”+ epoch +“,经过:”+字符串(d))drawnow结尾结尾结尾
微调后计算网络的分类精度。
cecurefacyFtraining = getNetworkAccuracy(Xtrain,Ytrain,params);fprintf('%.2F转移学习后的精度\ n',准确训练);
1.00转移学习后的精度
Helper Functions
本节提供了本示例中使用的助手功能的代码。
这getNetworkCcuracy
功能evaluates the network performance by calculating the classification accuracy.
功能精度= getNetWorkCcuracy(x,y,onnxparams)n = size(x,4);ypred = squeezenetfcn(x,onnxparams,'训练',错误的);[〜,yidx] = max(y,[],1);[〜,ypredidx] = max(ypred,[],1);numIncorrect = sum(abs(yidx-ypredidx)> 0);精度= 1 -numIncorct/n;结尾
这modelGradients
功能计算损失和梯度。
功能[grad,损失,状态] = modelgradients(x,y,onnxparams)[y,state] = squeezenetfcn(x,onnxparams,'训练',真的);损失= crossentropy(y,y,'DataFormat',,,,'CB');grad = dlgradient(loss,onnxParams.Learnables);结尾
这Squeezenetonnx
函数生成了一个ONNX模型squeezenet
网络。
功能Squeezenetonnx() exportONNXNetwork(squeezenet,'Squeezenet.onnx');结尾
移动参数被ONNX功能进口商错误标记
导入保存在ONNX格式的函数的网络,并通过使用使用错误标签的参数冻结
或者unfreeze
。
进口预处理SimpleNet.onnx
网络作为函数。simplenet
is a simple convolutional neural network trained on digit image data. For more information on how to createsimplenet
, 看创建简单的图像分类网络。
进口SimpleNet.onnx
使用experconnxfunction
,返回ONNXParameters
包含网络参数的对象。该函数还会在包含网络体系结构的当前文件夹中创建一个新的模型函数。将模型函数的名称指定为simplenetFcn
。
params = emumentOnnxFunction('simplenet.onnx',,,,'simplenetFcn');
包含导入的ONNX网络的函数已保存到文件SimpleNetfcn.m。要了解如何使用此功能,请键入:帮助SimpleEnetFCN。
experconnxfunction
将导入网络的参数标记为可学习的
(在培训期间更新的参数)或Nonlearnables
(在培训期间保持不变的参数)。标签并不总是准确的。建议的做法是检查参数是否分配给正确的结构参数。可学习的
或者参数
。显示导入网络的可学习和不可学习的参数。
参数。可学习的
ans =带有字段的结构:imageinput_mean: [1×1 dlarray] conv_W: [5×5×1×20 dlarray] conv_B: [20×1 dlarray] batchnorm_scale: [20×1 dlarray] batchnorm_B: [20×1 dlarray] fc_W: [24×24×20×10 dlarray] fc_B: [10×1 dlarray]
参数
ans =带有字段的结构:Convstride1004:[2×1 dlarray] ConvdilationFactor1005:[2×1 dlarray] Convpadding1006:[4×1 dlarray] Convstride1007:[2×1 dlarray] corvdilationFactor1008:
Note that参数。可学习的
包含参数imageinput_mean
,在培训期间应该保持不变(请参阅Mean
财产的ImageInputlayer
)。兑换imageinput_mean
到不可检测的参数。这冻结Parameters
函数删除参数imageinput_mean
fromparam.learnables
并将其添加到参数
顺序。
参数= freezeParameters(params,'imageinput_mean');
显示更新的可学习和不可学习的参数。
参数。可学习的
ans =带有字段的结构:CORS_W:[5×5×1×20 dlarray] Cons_b:[20×1 dlarray] batchnorm_scale:[20×1 dlarray] batchnorm_b:[20×1 dlarray] fc_w:[24×24×24×20×10×10 dlarray] fc_b:[10×1 dlarray]
参数
ans =带有字段的结构:ConvStride1004: [2×1 dlarray] ConvDilationFactor1005: [2×1 dlarray] ConvPadding1006: [4×1 dlarray] ConvStride1007: [2×1 dlarray] ConvDilationFactor1008: [2×1 dlarray] ConvPadding1009: [4×1 dlarray] imageinput_Mean:[1×1 dlarray]
Tips
这following rules apply when you assign a new value to a
参数。可学习的
parameter:该软件会自动将新值转换为
Dlarray
。新值必须与现有值兼容
params.numdimensions
。
experconnxfunction
得出结构的字段名称可学习的
,,,,Nonlearnables
, 和状态
从导入的ONNX模型文件中的名称中。导入网络之间的字段名称可能会有所不同。
版本历史记录
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
您单击了与此MATLAB命令相对应的链接:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
您还可以从以下列表中选择一个网站:
如何获得最佳网站性能
选择中国网站(中文或英语)以获得最佳场地性能。其他Mathworks乡村网站未针对您所在的访问进行优化。
美洲
- América Latina(Español)
- 加拿大(English)
- 美国(English)