Main Content

calibrate

深層ニューラル ネットワークのシミュレーションと範囲の収集

R2020a 以降

説明

calResults = calibrate(quantObj,calData) は、dlquantizer オブジェクト quantObj で指定されたネットワークについて、calData で指定されたデータを使用し、ネットワークを実行して、ネットワークの畳み込み層および全結合層の重みとバイアスのダイナミック レンジ、ならびにネットワークのすべての層内にある活性化のダイナミック レンジを収集します。

calResults = calibrate(quantObj,calData,Name,Value) は、1 つ以上の名前と値のペアの引数で指定された追加オプションを使用してネットワークのキャリブレーションを行います。

この関数を使用するには、Deep Learning Toolbox Model Quantization Library が必要です。深層ニューラル ネットワークの量子化に必要な製品については、量子化ワークフローの必要条件を参照してください。

すべて折りたたむ

この例では、GPU 用ニューラル ネットワークの畳み込み層の学習可能パラメーターを量子化し、量子化されたネットワークの動作を調べる方法を説明します。この例では、新しいイメージを分類するための深層学習ネットワークの学習の例に従って、新しいイメージを分類できるように squeezenet ニューラル ネットワークに再学習させた後、このネットワークを量子化します。この例では、ネットワークに必要なメモリ量が量子化によって約 75% 減少しますが、ネットワークの精度は影響を受けません。

事前学習済みのネットワークを読み込みます。net は、新しいイメージを分類するための深層学習ネットワークの学習の例で出力されたネットワークです。

load squeezenetmerch
net
net = 
  DAGNetwork with properties:

         Layers: [68×1 nnet.cnn.layer.Layer]
    Connections: [75×2 table]
     InputNames: {'data'}
    OutputNames: {'new_classoutput'}

量子化に使用するキャリブレーション データと検証データを定義します。

キャリブレーション データは、ネットワークの畳み込み層および全結合層の重みとバイアスのダイナミック レンジ、ならびにネットワークのすべての層内にあるアクティベーションのダイナミック レンジを収集するのに使用します。量子化によって最適な結果を得るには、キャリブレーション データがネットワークへの入力を典型的に表すものでなければなりません。

量子化を行った後、検証データを使用してネットワークをテストし、範囲を制限したことによる影響、および量子化後におけるネットワークの畳み込み層の精度を調べます。

この例では、MerchData データ セットのイメージを使用します。ネットワークで使用するデータのサイズを変更するための augmentedImageDatastore オブジェクトを定義します。その後、このデータをキャリブレーション データ セットと検証データ セットに分割します。

unzip('MerchData.zip');
imds = imageDatastore('MerchData', ...
    'IncludeSubfolders',true, ...
    'LabelSource','foldernames');
[calData, valData] = splitEachLabel(imds, 0.7, 'randomized');
aug_calData = augmentedImageDatastore([227 227], calData);
aug_valData = augmentedImageDatastore([227 227], valData);

dlquantizer オブジェクトを作成し、量子化するネットワークを指定します。

quantObj = dlquantizer(net);

量子化の前後のネットワークの動作を比較するために使用されるメトリクス関数を定義します。この例では、メトリクス関数 hComputeModelAccuracy を使用します。

function accuracy = hComputeModelAccuracy(predictionScores, net, dataStore)
%% Computes model-level accuracy statistics
    
    % Load ground truth
    tmp = readall(dataStore);
    groundTruth = tmp.response;
    
    % Compare with predicted label with actual ground truth 
    predictionError = {};
    for idx=1:numel(groundTruth)
        [~, idy] = max(predictionScores(idx,:)); 
        yActual = net.Layers(end).Classes(idy);
        predictionError{end+1} = (yActual == groundTruth(idx)); %#ok
    end
    
    % Sum all prediction errors.
    predictionError = [predictionError{:}];
    accuracy = sum(predictionError)/numel(predictionError);
end

dlquantizationOptions オブジェクトのメトリクス関数を指定します。

quantOpts = dlquantizationOptions('MetricFcn',{@(x)hComputeModelAccuracy(x, net, aug_valData)});

関数 calibrate を使用して、サンプル入力でネットワークを実行し、範囲情報を収集します。関数 calibrate は、ネットワークを実行し、ネットワークの畳み込み層と全結合層の重みとバイアスのダイナミック レンジ、およびネットワークのすべての層内の活性化のダイナミック レンジを収集します。この関数はテーブルを返します。テーブルの各行に、最適化されたネットワークの学習可能パラメーターの範囲情報が含まれています。

calResults = calibrate(quantObj, aug_calData)
calResults=121×5 table
        Optimized Layer Name         Network Layer Name     Learnables / Activations    MinValue     MaxValue
    ____________________________    ____________________    ________________________    _________    ________

    {'conv1_Weights'           }    {'conv1'           }           "Weights"             -0.91985     0.88489
    {'conv1_Bias'              }    {'conv1'           }           "Bias"                -0.07925     0.26343
    {'fire2-squeeze1x1_Weights'}    {'fire2-squeeze1x1'}           "Weights"                -1.38      1.2477
    {'fire2-squeeze1x1_Bias'   }    {'fire2-squeeze1x1'}           "Bias"                -0.11641     0.24273
    {'fire2-expand1x1_Weights' }    {'fire2-expand1x1' }           "Weights"              -0.7406     0.90982
    {'fire2-expand1x1_Bias'    }    {'fire2-expand1x1' }           "Bias"               -0.060056     0.14602
    {'fire2-expand3x3_Weights' }    {'fire2-expand3x3' }           "Weights"             -0.74397     0.66905
    {'fire2-expand3x3_Bias'    }    {'fire2-expand3x3' }           "Bias"               -0.051778    0.074239
    {'fire3-squeeze1x1_Weights'}    {'fire3-squeeze1x1'}           "Weights"              -0.7712     0.68917
    {'fire3-squeeze1x1_Bias'   }    {'fire3-squeeze1x1'}           "Bias"                -0.10138     0.32675
    {'fire3-expand1x1_Weights' }    {'fire3-expand1x1' }           "Weights"             -0.72035      0.9743
    {'fire3-expand1x1_Bias'    }    {'fire3-expand1x1' }           "Bias"               -0.067029     0.30425
    {'fire3-expand3x3_Weights' }    {'fire3-expand3x3' }           "Weights"             -0.61443      0.7741
    {'fire3-expand3x3_Bias'    }    {'fire3-expand3x3' }           "Bias"               -0.053613     0.10329
    {'fire4-squeeze1x1_Weights'}    {'fire4-squeeze1x1'}           "Weights"              -0.7422      1.0877
    {'fire4-squeeze1x1_Bias'   }    {'fire4-squeeze1x1'}           "Bias"                -0.10885     0.13881
      ⋮

関数 validate を使用して、ネットワークの畳み込み層内の学習可能パラメーターを量子化し、ネットワークを実行します。この関数は、量子化の前後のネットワークの結果を比較するために dlquantizationOptions オブジェクトで定義されたメトリクス関数を使用します。

valResults = validate(quantObj, aug_valData, quantOpts)
valResults = struct with fields:
       NumSamples: 20
    MetricResults: [1×1 struct]
       Statistics: [2×2 table]

検証出力を調べ、量子化後のネットワークのパフォーマンスを確認します。

valResults.MetricResults.Result
ans=2×2 table
    NetworkImplementation    MetricOutput
    _____________________    ____________

     {'Floating-Point'}           1      
     {'Quantized'     }           1      

valResults.Statistics
ans=2×2 table
    NetworkImplementation    LearnableParameterMemory(bytes)
    _____________________    _______________________________

     {'Floating-Point'}                2.9003e+06           
     {'Quantized'     }                7.3393e+05           

この例では、ネットワークに必要なメモリ量が量子化によって約 75% 減少しました。ネットワークの精度は影響を受けていません。

これで、dlquantizer オブジェクトで指定されたネットワークの畳み込み層の重み、バイアス、および活性化に、スケーリングされた 8 ビット整数データ型が使用されるようになりました。

畳み込み層の重み、バイアス、および活性化を、8 ビットにスケーリングされた整数データ型に量子化することで、深層ニューラル ネットワークのメモリ フットプリントを削減します。この例では、Deep Learning Toolbox Model Quantization Library と Deep Learning HDL Toolbox を使用して、int8 ネットワークをターゲット FPGA ボードに展開する方法を示します。

この例では、次が必要です。

  • Deep Learning Toolbox ™

  • Deep Learning HDL Toolbox ™

  • Deep Learning Toolbox Model Quantization Library

  • Deep Learning HDL Toolbox Support Package for Xilinx FPGA and SoC Devices

  • MATLAB Coder Interface for Deep Learning。

事前学習済みのネットワークの読み込み

事前学習済みの LogoNet ネットワークを読み込み、ネットワーク アーキテクチャを解析します。

snet = getLogoNetwork;
deepNetworkDesigner(snet);

データの読み込み

この例では logos_dataset データ セットを使用します。データ セットは 320 個のイメージで構成されています。各イメージのサイズは 227×227 で 3 つのカラー チャネル (RGB) があります。キャリブレーションと検証のためのaugmentedImageDatastoreオブジェクトを作成します。キャリブレーション データ セットを 20 個のイメージに減らすことで、キャリブレーションと検証を迅速化します。MATLAB シミュレーション ワークフローでは、量子化されたネットワークを検証する際のイメージの最大数が 5 に制限されています。検証データ セットのサイズを 5 つのイメージまで減らします。FPGA 検証ワークフローでは、量子化されたネットワークを検証する際のイメージの最大数が 1 に制限されています。FPGA 検証データ セットを 1 つのイメージまで減らします。

curDir = pwd;
unzip("logos_dataset.zip");
imageData = imageDatastore(fullfile(curDir,'logos_dataset'),...
'IncludeSubfolders',true,'FileExtensions','.JPG','LabelSource','foldernames');
[calibrationData, validationData] = splitEachLabel(imageData, 0.5,'randomized');
calibrationData_reduced = calibrationData.subset(1:20);
validationData_simulation = validationData.subset(1:5);
validationData_FPGA = validationData.subset(1:1);

ネットワーク用のキャリブレーション結果ファイルの生成

dlquantizer (Deep Learning HDL Toolbox)オブジェクトを作成し、量子化するネットワークを指定します。実行環境を FPGA として指定します。

dlQuantObj_simulation = dlquantizer(snet,'ExecutionEnvironment',"FPGA",'Simulation','on');
dlQuantObj_FPGA = dlquantizer(snet,'ExecutionEnvironment',"FPGA");

関数calibrate (Deep Learning HDL Toolbox)を使用して、サンプル入力でネットワークを実行し、範囲情報を収集します。関数 calibrate は、重みとバイアスのダイナミック レンジを収集します。関数 calibrate は table を返します。テーブルの各行に、量子化されたネットワークの学習可能パラメーターの範囲情報が含まれています。

calibrate(dlQuantObj_simulation,calibrationData_reduced)
ans=35×5 table
        Optimized Layer Name        Network Layer Name    Learnables / Activations     MinValue       MaxValue 
    ____________________________    __________________    ________________________    ___________    __________

    {'conv_1_Weights'          }      {'conv_1'    }           "Weights"                -0.048978      0.039352
    {'conv_1_Bias'             }      {'conv_1'    }           "Bias"                     0.99996        1.0028
    {'conv_2_Weights'          }      {'conv_2'    }           "Weights"                -0.055518      0.061901
    {'conv_2_Bias'             }      {'conv_2'    }           "Bias"                 -0.00061171       0.00227
    {'conv_3_Weights'          }      {'conv_3'    }           "Weights"                -0.045942      0.046927
    {'conv_3_Bias'             }      {'conv_3'    }           "Bias"                  -0.0013998     0.0015218
    {'conv_4_Weights'          }      {'conv_4'    }           "Weights"                -0.045967         0.051
    {'conv_4_Bias'             }      {'conv_4'    }           "Bias"                    -0.00164     0.0037892
    {'fc_1_Weights'            }      {'fc_1'      }           "Weights"                -0.051394      0.054344
    {'fc_1_Bias'               }      {'fc_1'      }           "Bias"                 -0.00052319    0.00084454
    {'fc_2_Weights'            }      {'fc_2'      }           "Weights"                 -0.05016      0.051557
    {'fc_2_Bias'               }      {'fc_2'      }           "Bias"                  -0.0017564     0.0018502
    {'fc_3_Weights'            }      {'fc_3'      }           "Weights"                -0.050706       0.04678
    {'fc_3_Bias'               }      {'fc_3'      }           "Bias"                    -0.02951      0.024855
    {'imageinput'              }      {'imageinput'}           "Activations"                    0           255
    {'imageinput_normalization'}      {'imageinput'}           "Activations"              -139.34        193.72
      ⋮

calibrate(dlQuantObj_FPGA,calibrationData_reduced)
ans=35×5 table
        Optimized Layer Name        Network Layer Name    Learnables / Activations     MinValue       MaxValue 
    ____________________________    __________________    ________________________    ___________    __________

    {'conv_1_Weights'          }      {'conv_1'    }           "Weights"                -0.048978      0.039352
    {'conv_1_Bias'             }      {'conv_1'    }           "Bias"                     0.99996        1.0028
    {'conv_2_Weights'          }      {'conv_2'    }           "Weights"                -0.055518      0.061901
    {'conv_2_Bias'             }      {'conv_2'    }           "Bias"                 -0.00061171       0.00227
    {'conv_3_Weights'          }      {'conv_3'    }           "Weights"                -0.045942      0.046927
    {'conv_3_Bias'             }      {'conv_3'    }           "Bias"                  -0.0013998     0.0015218
    {'conv_4_Weights'          }      {'conv_4'    }           "Weights"                -0.045967         0.051
    {'conv_4_Bias'             }      {'conv_4'    }           "Bias"                    -0.00164     0.0037892
    {'fc_1_Weights'            }      {'fc_1'      }           "Weights"                -0.051394      0.054344
    {'fc_1_Bias'               }      {'fc_1'      }           "Bias"                 -0.00052319    0.00084454
    {'fc_2_Weights'            }      {'fc_2'      }           "Weights"                 -0.05016      0.051557
    {'fc_2_Bias'               }      {'fc_2'      }           "Bias"                  -0.0017564     0.0018502
    {'fc_3_Weights'            }      {'fc_3'      }           "Weights"                -0.050706       0.04678
    {'fc_3_Bias'               }      {'fc_3'      }           "Bias"                    -0.02951      0.024855
    {'imageinput'              }      {'imageinput'}           "Activations"                    0           255
    {'imageinput_normalization'}      {'imageinput'}           "Activations"              -139.34        193.72
      ⋮

ターゲット オブジェクトの作成

ターゲット デバイスのカスタム名をもつターゲット オブジェクト、およびターゲット デバイスをホスト コンピューターに接続するためのインターフェイスを作成します。インターフェイス オプションは、JTAG とイーサネットです。JTAG を使用するには、Xilinx™ Vivado™ Design Suite 2020.2 をインストールします。Xilinx Vivado ツールパスを設定するには、次のように入力します。

% hdlsetuptoolpath('ToolName', 'Xilinx Vivado', 'ToolPath', 'C:\Xilinx\Vivado\2020.2\bin\vivado.bat');

ターゲット オブジェクトを作成するには、次のように入力します。

hTarget = dlhdl.Target('Xilinx','Interface','Ethernet');

あるいは、JTAG インターフェイスを使用することもできます。

% hTarget = dlhdl.Target('Xilinx', 'Interface', 'JTAG');

dlQuantizationOptions オブジェクトの作成

dlquantizationOptions オブジェクトを作成します。ターゲット ビットストリームとターゲット ボード インターフェイスを指定します。既定のメトリクス関数は、最上位精度のメトリクス関数です。

options_FPGA = dlquantizationOptions('Bitstream','zcu102_int8','Target',hTarget);
options_simulation = dlquantizationOptions;

カスタム メトリクス関数を使用するには、dlquantizationOptions オブジェクトでメトリクス関数を指定します。

options_FPGA = dlquantizationOptions('MetricFcn',{@(x)hComputeAccuracy(x,snet,validationData_FPGA)},'Bitstream','zcu102_int8','Target',hTarget);
options_simulation = dlquantizationOptions('MetricFcn',{@(x)hComputeAccuracy(x,snet,validationData_simulation)})

量子化ネットワークの検証

関数 validate を使用して、ネットワークの畳み込み層内の学習可能パラメーターを量子化します。関数 validate は、量子化されたネットワークを MATLAB でシミュレーションします。関数 validate は、dlquantizationOptions オブジェクトで定義されたメトリクス関数を使用して、単一データ型のネットワーク オブジェクトの結果と量子化されたネットワーク オブジェクトの結果を比較します。

prediction_simulation = dlQuantObj_simulation.validate(validationData_simulation,options_simulation)
Compiling leg: conv_1>>relu_4 ...
Compiling leg: conv_1>>relu_4 ... complete.
Compiling leg: maxpool_4 ...
Compiling leg: maxpool_4 ... complete.
Compiling leg: fc_1>>fc_3 ...
Compiling leg: fc_1>>fc_3 ... complete.
prediction_simulation = struct with fields:
       NumSamples: 5
    MetricResults: [1×1 struct]
       Statistics: []

FPGA での検証の場合、関数 validate は以下を行います。

  • compile メソッドの出力とプログラミング ファイルを使用して FPGA ボードをプログラムする

  • ネットワークの重みとバイアスをダウンロードする

  • 量子化前後のネットワークのパフォーマンスを比較する

prediction_FPGA = dlQuantObj_FPGA.validate(validationData_FPGA,options_FPGA)
### Compiling network for Deep Learning FPGA prototyping ...
### Targeting FPGA bitstream zcu102_int8.
### The network includes the following layers:
     1   'imageinput'    Image Input             227×227×3 images with 'zerocenter' normalization and 'randfliplr' augmentations  (SW Layer)
     2   'conv_1'        Convolution             96 5×5×3 convolutions with stride [1  1] and padding [0  0  0  0]                (HW Layer)
     3   'relu_1'        ReLU                    ReLU                                                                             (HW Layer)
     4   'maxpool_1'     Max Pooling             3×3 max pooling with stride [2  2] and padding [0  0  0  0]                      (HW Layer)
     5   'conv_2'        Convolution             128 3×3×96 convolutions with stride [1  1] and padding [0  0  0  0]              (HW Layer)
     6   'relu_2'        ReLU                    ReLU                                                                             (HW Layer)
     7   'maxpool_2'     Max Pooling             3×3 max pooling with stride [2  2] and padding [0  0  0  0]                      (HW Layer)
     8   'conv_3'        Convolution             384 3×3×128 convolutions with stride [1  1] and padding [0  0  0  0]             (HW Layer)
     9   'relu_3'        ReLU                    ReLU                                                                             (HW Layer)
    10   'maxpool_3'     Max Pooling             3×3 max pooling with stride [2  2] and padding [0  0  0  0]                      (HW Layer)
    11   'conv_4'        Convolution             128 3×3×384 convolutions with stride [2  2] and padding [0  0  0  0]             (HW Layer)
    12   'relu_4'        ReLU                    ReLU                                                                             (HW Layer)
    13   'maxpool_4'     Max Pooling             3×3 max pooling with stride [2  2] and padding [0  0  0  0]                      (HW Layer)
    14   'fc_1'          Fully Connected         2048 fully connected layer                                                       (HW Layer)
    15   'relu_5'        ReLU                    ReLU                                                                             (HW Layer)
    16   'dropout_1'     Dropout                 50% dropout                                                                      (HW Layer)
    17   'fc_2'          Fully Connected         2048 fully connected layer                                                       (HW Layer)
    18   'relu_6'        ReLU                    ReLU                                                                             (HW Layer)
    19   'dropout_2'     Dropout                 50% dropout                                                                      (HW Layer)
    20   'fc_3'          Fully Connected         32 fully connected layer                                                         (HW Layer)
    21   'softmax'       Softmax                 softmax                                                                          (HW Layer)
    22   'classoutput'   Classification Output   crossentropyex with 'adidas' and 31 other classes                                (SW Layer)
                                                                                                                                
### Notice: The layer 'imageinput' with type 'nnet.cnn.layer.ImageInputLayer' is implemented in software.
### Notice: The layer 'softmax' with type 'nnet.cnn.layer.SoftmaxLayer' is implemented in software.
### Notice: The layer 'classoutput' with type 'nnet.cnn.layer.ClassificationOutputLayer' is implemented in software.
### Compiling layer group: conv_1>>relu_4 ...
### Compiling layer group: conv_1>>relu_4 ... complete.
### Compiling layer group: maxpool_4 ...
### Compiling layer group: maxpool_4 ... complete.
### Compiling layer group: fc_1>>fc_3 ...
### Compiling layer group: fc_1>>fc_3 ... complete.

### Allocating external memory buffers:

          offset_name          offset_address    allocated_space 
    _______________________    ______________    ________________

    "InputDataOffset"           "0x00000000"     "12.0 MB"       
    "OutputResultOffset"        "0x00c00000"     "4.0 MB"        
    "SchedulerDataOffset"       "0x01000000"     "4.0 MB"        
    "SystemBufferOffset"        "0x01400000"     "36.0 MB"       
    "InstructionDataOffset"     "0x03800000"     "8.0 MB"        
    "ConvWeightDataOffset"      "0x04000000"     "12.0 MB"       
    "FCWeightDataOffset"        "0x04c00000"     "12.0 MB"       
    "EndOffset"                 "0x05800000"     "Total: 88.0 MB"

### Network compilation complete.

### FPGA bitstream programming has been skipped as the same bitstream is already loaded on the target FPGA.
### Deep learning network programming has been skipped as the same network is already loaded on the target FPGA.
### Finished writing input activations.
### Running single input activation.


              Deep Learning Processor Bitstream Build Info

Resource                   Utilized           Total        Percentage
------------------        ----------      ------------    ------------
LUTs (CLB/ALM)*              248358            274080           90.62
DSPs                            384              2520           15.24
Block RAM                       581               912           63.71
* LUT count represents Configurable Logic Block(CLB) utilization in Xilinx devices and Adaptive Logic Module (ALM) utilization in Intel devices.

### Notice: The layer 'imageinput' of type 'ImageInputLayer' is split into an image input layer 'imageinput' and an addition layer 'imageinput_norm' for normalization on hardware.
### Notice: The layer 'softmax' with type 'nnet.cnn.layer.SoftmaxLayer' is implemented in software.
### Notice: The layer 'classoutput' with type 'nnet.cnn.layer.ClassificationOutputLayer' is implemented in software.


              Deep Learning Processor Estimator Performance Results

                   LastFrameLatency(cycles)   LastFrameLatency(seconds)       FramesNum      Total Latency     Frames/s
                         -------------             -------------              ---------        ---------       ---------
Network                   40142478                  0.18247                       1           40142478              5.5
    ____imageinput_norm     216472                  0.00098 
    ____conv_1             6825671                  0.03103 
    ____maxpool_1          3755088                  0.01707 
    ____conv_2            10440701                  0.04746 
    ____maxpool_2          1447840                  0.00658 
    ____conv_3             9405685                  0.04275 
    ____maxpool_3          1765856                  0.00803 
    ____conv_4             1819636                  0.00827 
    ____maxpool_4            28098                  0.00013 
    ____fc_1               2651288                  0.01205 
    ____fc_2               1696632                  0.00771 
    ____fc_3                 89511                  0.00041 
 * The clock frequency of the DL processor is: 220MHz




              Deep Learning Processor Bitstream Build Info

Resource                   Utilized           Total        Percentage
------------------        ----------      ------------    ------------
LUTs (CLB/ALM)*              168645            274080           61.53
DSPs                            800              2520           31.75
Block RAM                       453               912           49.67
* LUT count represents Configurable Logic Block(CLB) utilization in Xilinx devices and Adaptive Logic Module (ALM) utilization in Intel devices.

### Finished writing input activations.
### Running single input activation.
prediction_FPGA = struct with fields:
       NumSamples: 1
    MetricResults: [1×1 struct]
       Statistics: [2×7 table]

量子化されたニューラル ネットワークのパフォーマンスの表示

量子化されたネットワークの精度を表示します。

prediction_simulation.MetricResults.Result
ans=2×2 table
    NetworkImplementation    MetricOutput
    _____________________    ____________

     {'Floating-Point'}           1      
     {'Quantized'     }           1      

prediction_FPGA.MetricResults.Result
ans=2×2 table
    NetworkImplementation    MetricOutput
    _____________________    ____________

     {'Floating-Point'}           1      
     {'Quantized'     }           1      

量子化されたネットワークのパフォーマンスを 1 秒あたりのフレーム数で表示します。

prediction_FPGA.Statistics.FramesPerSecond(2)
ans = 19.0828

この例では、CPU ターゲット用のニューラル ネットワークの量子化と検証を行う方法を説明します。このワークフローは、他の実行環境の場合と同様ですが、検証を行う前に raspi 接続を確立し、dlquantizationOptions を使用してそれをターゲットとして指定しなければなりません。

まず、ネットワークを読み込みます。この例では、事前学習済みのネットワーク squeezenet を使用します。

load squeezenetmerch
net
net = 
  DAGNetwork with properties:

         Layers: [68×1 nnet.cnn.layer.Layer]
    Connections: [75×2 table]
     InputNames: {'data'}
    OutputNames: {'new_classoutput'}

次に、キャリブレーション データ calDS と検証データ valDS を定義します。

unzip('MerchData.zip');
imds = imageDatastore('MerchData', ...
    'IncludeSubfolders',true, ...
    'LabelSource','foldernames');
[calData, valData] = splitEachLabel(imds, 0.7, 'randomized');
aug_calData = augmentedImageDatastore([227 227],calData);
aug_valData = augmentedImageDatastore([227 227],valData);

dlquantizer オブジェクトを作成し、CPU の実行環境を指定します。

dq =  dlquantizer(net,'ExecutionEnvironment','CPU') 
dq = 
  dlquantizer with properties:

           NetworkObject: [1×1 DAGNetwork]
    ExecutionEnvironment: 'CPU'

ネットワークのキャリブレーションを実行します。

calResults = calibrate(dq,aug_calData,'UseGPU','off')
calResults=122×5 table
        Optimized Layer Name         Network Layer Name     Learnables / Activations    MinValue     MaxValue
    ____________________________    ____________________    ________________________    _________    ________

    {'conv1_Weights'           }    {'conv1'           }           "Weights"             -0.91985     0.88489
    {'conv1_Bias'              }    {'conv1'           }           "Bias"                -0.07925     0.26343
    {'fire2-squeeze1x1_Weights'}    {'fire2-squeeze1x1'}           "Weights"                -1.38      1.2477
    {'fire2-squeeze1x1_Bias'   }    {'fire2-squeeze1x1'}           "Bias"                -0.11641     0.24273
    {'fire2-expand1x1_Weights' }    {'fire2-expand1x1' }           "Weights"              -0.7406     0.90982
    {'fire2-expand1x1_Bias'    }    {'fire2-expand1x1' }           "Bias"               -0.060056     0.14602
    {'fire2-expand3x3_Weights' }    {'fire2-expand3x3' }           "Weights"             -0.74397     0.66905
    {'fire2-expand3x3_Bias'    }    {'fire2-expand3x3' }           "Bias"               -0.051778    0.074239
    {'fire3-squeeze1x1_Weights'}    {'fire3-squeeze1x1'}           "Weights"              -0.7712     0.68917
    {'fire3-squeeze1x1_Bias'   }    {'fire3-squeeze1x1'}           "Bias"                -0.10138     0.32675
    {'fire3-expand1x1_Weights' }    {'fire3-expand1x1' }           "Weights"             -0.72035      0.9743
    {'fire3-expand1x1_Bias'    }    {'fire3-expand1x1' }           "Bias"               -0.067029     0.30425
    {'fire3-expand3x3_Weights' }    {'fire3-expand3x3' }           "Weights"             -0.61443      0.7741
    {'fire3-expand3x3_Bias'    }    {'fire3-expand3x3' }           "Bias"               -0.053613     0.10329
    {'fire4-squeeze1x1_Weights'}    {'fire4-squeeze1x1'}           "Weights"              -0.7422      1.0877
    {'fire4-squeeze1x1_Bias'   }    {'fire4-squeeze1x1'}           "Bias"                -0.10885     0.13881
      ⋮

MATLAB Support Package for Raspberry Pi Hardware の関数 raspi を使用して、Raspberry Pi への接続を作成します。以下のコードで、次を置き換えます。

  • raspiname: Raspberry Pi の名前またはアドレス

  • username: 自分のユーザー名

  • password: 自分のパスワード

% r = raspi('raspiname','username','password')

次に例を示します。

r = raspi('gpucoder-raspberrypi-7','pi','matlab')
r = 
  raspi with properties:

         DeviceAddress: 'gpucoder-raspberrypi-7'      
                  Port: 18734                         
             BoardName: 'Raspberry Pi 3 Model B+'     
         AvailableLEDs: {'led0'}                      
  AvailableDigitalPins: [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
  AvailableSPIChannels: {}                            
     AvailableI2CBuses: {}                            
      AvailableWebcams: {}                            
           I2CBusSpeed:                               
AvailableCANInterfaces: {}                            

  Supported peripherals

raspi オブジェクトを量子化ネットワークのターゲットとして指定します。

opts = dlquantizationOptions('Target',r)
opts = 
  dlquantizationOptions with properties:

    MetricFcn: {}
    Bitstream: ''
       Target: [1×1 raspi]

関数 validate を使用して、量子化後のネットワークを検証します。

valResults = validate(dq,aug_valData,opts)
### Starting application: 'codegen\lib\validate_predict_int8\pil\validate_predict_int8.elf'
    To terminate execution: clear validate_predict_int8_pil
### Launching application validate_predict_int8.elf...
### Host application produced the following standard output (stdout) and standard error (stderr) messages:
valResults = struct with fields:
       NumSamples: 20
    MetricResults: [1×1 struct]
       Statistics: []

検証出力を調べ、量子化後のネットワークのパフォーマンスを確認します。

valResults.MetricResults.Result
ans=2×2 table
    NetworkImplementation    MetricOutput
    _____________________    ____________

     {'Floating-Point'}          0.95    
     {'Quantized'     }          0.95    

この例では、前処理済みのキャリブレーションと検証データを使用してyolov3ObjectDetector (Computer Vision Toolbox)オブジェクトを量子化する方法を示します。

まず、事前学習済みの YOLO v3 オブジェクト検出器をダウンロードします。

detector = downloadPretrainedNetwork();

この例では、1 つまたは 2 つのラベル付きの車両インスタンスを含む小さなラベル付きデータ セットを使用します。これらのイメージの多くは、Caltech の Cars 1999 データ セットおよび Cars 2001 データ セットからのものです。Pietro Perona 氏によって作成されたもので、許可を得て使用しています。

車両のイメージを解凍し、車両のグラウンド トゥルース データを読み込みます。

unzip vehicleDatasetImages.zip
data = load('vehicleDatasetGroundTruth.mat');
vehicleDataset = data.vehicleDataset;

ローカルの車両データ フォルダーへの絶対パスを追加します。

vehicleDataset.imageFilename = fullfile(pwd, vehicleDataset.imageFilename);

イメージを読み込むためのimageDatastoreと、グラウンド トゥルース境界ボックスのためのboxLabelDatastore (Computer Vision Toolbox)を作成します。

imds = imageDatastore(vehicleDataset.imageFilename);
blds = boxLabelDatastore(vehicleDataset(:,2));

関数combineを使用して、両方のデータストアをCombinedDatastoreに結合します。

combinedDS = combine(imds, blds);

データをキャリブレーション データと検証データに分割します。

calData = combinedDS.subset(1:32);
valData = combinedDS.subset(33:64);

yolov3ObjectDetector (Computer Vision Toolbox)オブジェクトのpreprocess (Computer Vision Toolbox)メソッドを関数transformとともに使用して、キャリブレーションと検証用のデータを準備します。

関数transformTransformedDatastoreオブジェクトを返します。

processedCalData = transform(calData, @(data)preprocess(detector,data));
processedValData = transform(valData, @(data)preprocess(detector,data));

dlquantizer オブジェクトを作成します。

dq = dlquantizer(detector, 'ExecutionEnvironment', 'MATLAB');

ネットワークのキャリブレーションを実行します。

calResults = calibrate(dq, processedCalData,'UseGPU','off')
calResults=135×5 table
        Optimized Layer Name         Network Layer Name     Learnables / Activations    MinValue     MaxValue
    ____________________________    ____________________    ________________________    _________    ________

    {'conv1_Weights'           }    {'conv1'           }           "Weights"             -0.92189     0.85687
    {'conv1_Bias'              }    {'conv1'           }           "Bias"               -0.096271     0.26628
    {'fire2-squeeze1x1_Weights'}    {'fire2-squeeze1x1'}           "Weights"              -1.3751      1.2444
    {'fire2-squeeze1x1_Bias'   }    {'fire2-squeeze1x1'}           "Bias"                -0.12068     0.23104
    {'fire2-expand1x1_Weights' }    {'fire2-expand1x1' }           "Weights"             -0.75275     0.91615
    {'fire2-expand1x1_Bias'    }    {'fire2-expand1x1' }           "Bias"               -0.059252     0.14035
    {'fire2-expand3x3_Weights' }    {'fire2-expand3x3' }           "Weights"             -0.75271      0.6774
    {'fire2-expand3x3_Bias'    }    {'fire2-expand3x3' }           "Bias"               -0.062214    0.088242
    {'fire3-squeeze1x1_Weights'}    {'fire3-squeeze1x1'}           "Weights"              -0.7586     0.68772
    {'fire3-squeeze1x1_Bias'   }    {'fire3-squeeze1x1'}           "Bias"                -0.10206     0.31645
    {'fire3-expand1x1_Weights' }    {'fire3-expand1x1' }           "Weights"             -0.71566     0.97678
    {'fire3-expand1x1_Bias'    }    {'fire3-expand1x1' }           "Bias"               -0.069313     0.32881
    {'fire3-expand3x3_Weights' }    {'fire3-expand3x3' }           "Weights"             -0.60079     0.77642
    {'fire3-expand3x3_Bias'    }    {'fire3-expand3x3' }           "Bias"               -0.058045     0.11229
    {'fire4-squeeze1x1_Weights'}    {'fire4-squeeze1x1'}           "Weights"               -0.738      1.0805
    {'fire4-squeeze1x1_Bias'   }    {'fire4-squeeze1x1'}           "Bias"                -0.11189     0.13698
      ⋮

関数 validate を使用して、量子化後のネットワークを検証します。

valResults = validate(dq, processedValData)
valResults = struct with fields:
       NumSamples: 32
    MetricResults: [1×1 struct]
       Statistics: []

function detector = downloadPretrainedNetwork()
   pretrainedURL = 'https://ssd.mathworks.com/supportfiles/vision/data/yolov3SqueezeNetVehicleExample_21aSPKG.zip';
   websave('yolov3SqueezeNetVehicleExample_21aSPKG.zip', pretrainedURL);

   unzip('yolov3SqueezeNetVehicleExample_21aSPKG.zip');

   pretrained = load("yolov3SqueezeNetVehicleExample_21aSPKG.mat");
   detector = pretrained.detector;
end    

入力引数

すべて折りたたむ

量子化するネットワーク。dlquantizer オブジェクトとして指定します。

量子化後のネットワークのキャリブレーションに使用するデータ。imageDatastore オブジェクト、augmentedImageDatastore オブジェクト、pixelLabelImageDatastore (Computer Vision Toolbox) オブジェクト、CombinedDatastore オブジェクト、または TransformedDatastore オブジェクトとして指定します。

yolov3ObjectDetector (Computer Vision Toolbox) オブジェクトのキャリブレーションに使用されるデータは、関数 preprocess (Computer Vision Toolbox) を使用して前処理しなければなりません。yolov3ObjectDetector のキャリブレーション用に前処理されたデータを使用する例については、YOLO v3 オブジェクト検出器の量子化を参照してください。

有効なデータストアの詳細については、Prepare Data for Quantizing Networksを参照してください。

名前と値の引数

オプションの引数のペアを Name1=Value1,...,NameN=ValueN として指定します。ここで、Name は引数名で、Value は対応する値です。名前と値の引数は他の引数の後に指定しなければなりませんが、ペアの順序は重要ではありません。

R2021a より前では、コンマを使用して名前と値をそれぞれ区切り、Name を引用符で囲みます。

例: calResults = calibrate(quantObj,calData,'UseGPU','on')

キャリブレーションで使用するミニバッチのサイズ。正の整数として指定します。ミニバッチのサイズが大きくなるとより多くのメモリが必要になりますが、キャリブレーション時間が短縮される可能性があります。

データ型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

キャリブレーションにホスト GPU を使用するかどうか。次のいずれかとして指定します。

  • 'auto' — 利用可能な場合、キャリブレーションにホスト GPU を使用します。それ以外の場合は、キャリブレーションに CPU を使用します。

  • 'on' — キャリブレーションにホスト GPU を使用します。

  • 'off' — キャリブレーションにホスト CPU を使用します。

データ型: char

出力引数

すべて折りたたむ

ネットワークの層のダイナミック レンジ。テーブルとして返されます。テーブルの各行に、最適化されたネットワークの畳み込み層の学習可能パラメーターの最小値と最大値が表示されます。ソフトウェアは、この最小値と最大値を使用して、量子化されたパラメーターのデータ型のスケーリングを決定します。

バージョン履歴

R2020a で導入

すべて展開する