Этот пример показывает, как преобразовать модель регрессии нейронной сети в Simulink к фиксированной точке с помощью функции fxpopt
и Оптимизатора Интерполяционной таблицы.
Fixed-Point Designer обеспечивает рабочие процессы через Инструмент Фиксированной точки, который может преобразовать проект от типов данных с плавающей точкой до типов данных с фиксированной точкой. Функция fxpopt
оптимизирует типы данных в основанном на модели в заданной системе поведенческие ограничения. Для получения дополнительной информации отошлите к ссылке на документацию https://www.mathworks.com/help/fixedpoint/ref/fxpopt.html, Оптимизатор Интерполяционной таблицы генерирует эффективные памятью замены интерполяционной таблицы для неограниченных функций, таких как exp
и log2
. Используя эти инструменты, этот пример демонстрирует, как преобразовать обученную модель регрессии нейронной сети с плавающей точкой, чтобы использовать встроено-эффективные типы данных с фиксированной точкой.
Neural Network Toolbox поставляется с engine_dataset, который содержит данные, представляющие отношение между топливным уровнем и скоростью механизма, и его крутящим моментом и выбросами газа.
% Use the Function fitting tool (nftool) from Neural Network Toolbox(TM) to % train a neural network to estimate torque and gas emissions of an engine % given the fuel rate and speed. Use the following commands to train % the neural network. load engine_dataset; x = engineInputs; t = engineTargets; net = fitnet(10); net = train(net,x,t); view(net)
Закройте все окна учебного инструмента и представление сети
nnet.guis.closeAllViews();
nntraintool('close');
Если сеть обучена, используйте функцию gensim
от Нейронной сети Toolbox™, чтобы сгенерировать модель Simulink.
[sysName, netName] = gensim(net, 'Name', 'mTrainedNN'); %#ok
Модель, сгенерированная функцией gensim
, содержит нейронную сеть с обученными весами и смещениями. Чтобы подготовить эту сгенерированную модель к преобразованию фиксированной точки, выполните шаги подготовки в инструкциях по лучшым практикам. https://www.mathworks.com/help/fixedpoint/ug/best-practices-for-using-the-fixed-point-tool-to-propose-data-types-for-your-simulink-model.html
После применения этих принципов обученная нейронная сеть далее изменяется, чтобы включить журналирование сигнала при выводе сети, добавить входные стимулы и блоки верификации. Измененная модель сохранена как fxpdemo_neuralnet_regression
Скопируйте модель во временную перезаписываемую директорию.
model = 'fxpdemo_neuralnet_regression'; current_dir = pwd; fxpnn_demo_dir = fullfile(matlabroot, 'toolbox', 'simulink', 'fixedandfloat', 'fxpdemos'); fxpnn_temp_dir = [tempdir 'fxpnn_dir']; cd(tempdir); [~, ~, ~] = rmdir(fxpnn_temp_dir, 's'); mkdir(fxpnn_temp_dir); cd(fxpnn_temp_dir); copyfile(fullfile(fxpnn_demo_dir, [model,'.slx']), fullfile(fxpnn_temp_dir, [model '_toconvert.slx']));
Открытый и модель Inspect
model = [model '_toconvert']; system_under_design = [model '/Function Fitting Neural Network']; baseline_output = [model '/yarr']; open_system(model); % Set up model for HDL code generation hdlsetup(model);
Моделируйте модель, чтобы наблюдать производительность модели при использовании типов данных с плавающей точкой с двойной точностью.
sim_out = sim(model, 'SaveFormat', 'Dataset'); plotRegression(sim_out, baseline_output, system_under_design, 'Regression before conversion');
opts = fxpOptimizationOptions(); opts.addTolerance(system_under_design, 1, 'RelTol', 0.05); opts.addTolerance(system_under_design, 1, 'AbsTol', 50) opts.AllowableWordLengths = 8:32;
Используйте функцию fxpopt
, чтобы оптимизировать типы данных в системе в соответствии с проектом и исследовать решение. Программное обеспечение анализирует область значений объектов в system_under_design
и wordlength и ограничениях допуска, заданных в opts
, чтобы применить типы гетерогенных данных к модели при минимизации общей битной ширины.
solution = fxpopt(model, system_under_design, opts);
best_solution = solution.explore; %#ok
+ Preprocessing + Modeling the optimization problem - Constructing decision variables + Running the optimization solver - Evaluating new solution: cost 480, does not meet the tolerances. - Evaluating new solution: cost 540, does not meet the tolerances. - Evaluating new solution: cost 600, does not meet the tolerances. - Evaluating new solution: cost 660, does not meet the tolerances. - Evaluating new solution: cost 720, does not meet the tolerances. - Evaluating new solution: cost 780, does not meet the tolerances. - Evaluating new solution: cost 840, does not meet the tolerances. - Evaluating new solution: cost 900, meets the tolerances. - Updated best found solution, cost: 900 - Evaluating new solution: cost 896, meets the tolerances. - Updated best found solution, cost: 896 - Evaluating new solution: cost 886, meets the tolerances. - Updated best found solution, cost: 886 - Evaluating new solution: cost 885, meets the tolerances. - Updated best found solution, cost: 885 - Evaluating new solution: cost 884, meets the tolerances. - Updated best found solution, cost: 884 - Evaluating new solution: cost 883, meets the tolerances. - Updated best found solution, cost: 883 - Evaluating new solution: cost 882, meets the tolerances. - Updated best found solution, cost: 882 - Evaluating new solution: cost 881, meets the tolerances. - Updated best found solution, cost: 881 - Evaluating new solution: cost 880, meets the tolerances. - Updated best found solution, cost: 880 - Evaluating new solution: cost 879, meets the tolerances. - Updated best found solution, cost: 879 - Evaluating new solution: cost 878, meets the tolerances. - Updated best found solution, cost: 878 - Evaluating new solution: cost 868, meets the tolerances. - Updated best found solution, cost: 868 - Evaluating new solution: cost 867, meets the tolerances. - Updated best found solution, cost: 867 - Evaluating new solution: cost 866, meets the tolerances. - Updated best found solution, cost: 866 - Evaluating new solution: cost 865, meets the tolerances. - Updated best found solution, cost: 865 - Evaluating new solution: cost 864, meets the tolerances. - Updated best found solution, cost: 864 - Evaluating new solution: cost 863, meets the tolerances. - Updated best found solution, cost: 863 - Evaluating new solution: cost 862, meets the tolerances. - Updated best found solution, cost: 862 - Evaluating new solution: cost 857, meets the tolerances. - Updated best found solution, cost: 857 - Evaluating new solution: cost 856, meets the tolerances. - Updated best found solution, cost: 856 - Evaluating new solution: cost 855, meets the tolerances. - Updated best found solution, cost: 855 - Evaluating new solution: cost 850, does not meet the tolerances. - Evaluating new solution: cost 854, meets the tolerances. - Updated best found solution, cost: 854 - Evaluating new solution: cost 846, meets the tolerances. - Updated best found solution, cost: 846 - Evaluating new solution: cost 845, meets the tolerances. - Updated best found solution, cost: 845 - Evaluating new solution: cost 841, does not meet the tolerances. - Evaluating new solution: cost 835, meets the tolerances. - Updated best found solution, cost: 835 - Evaluating new solution: cost 834, meets the tolerances. - Updated best found solution, cost: 834 - Evaluating new solution: cost 833, meets the tolerances. - Updated best found solution, cost: 833 - Evaluating new solution: cost 832, meets the tolerances. - Updated best found solution, cost: 832 - Evaluating new solution: cost 831, meets the tolerances. - Updated best found solution, cost: 831 - Evaluating new solution: cost 830, meets the tolerances. - Updated best found solution, cost: 830 - Evaluating new solution: cost 829, meets the tolerances. - Updated best found solution, cost: 829 - Evaluating new solution: cost 828, meets the tolerances. - Updated best found solution, cost: 828 - Evaluating new solution: cost 827, meets the tolerances. - Updated best found solution, cost: 827 - Evaluating new solution: cost 817, meets the tolerances. - Updated best found solution, cost: 817 - Evaluating new solution: cost 816, meets the tolerances. - Updated best found solution, cost: 816 - Evaluating new solution: cost 815, meets the tolerances. - Updated best found solution, cost: 815 - Evaluating new solution: cost 814, meets the tolerances. - Updated best found solution, cost: 814 - Evaluating new solution: cost 813, meets the tolerances. - Updated best found solution, cost: 813 - Evaluating new solution: cost 812, meets the tolerances. - Updated best found solution, cost: 812 - Evaluating new solution: cost 811, meets the tolerances. - Updated best found solution, cost: 811 - Evaluating new solution: cost 806, meets the tolerances. - Updated best found solution, cost: 806 - Evaluating new solution: cost 805, meets the tolerances. - Updated best found solution, cost: 805 - Evaluating new solution: cost 804, meets the tolerances. - Updated best found solution, cost: 804 - Evaluating new solution: cost 799, does not meet the tolerances. - Evaluating new solution: cost 803, does not meet the tolerances. - Evaluating new solution: cost 796, meets the tolerances. - Updated best found solution, cost: 796 - Evaluating new solution: cost 795, meets the tolerances. - Updated best found solution, cost: 795 - Evaluating new solution: cost 791, meets the tolerances. - Updated best found solution, cost: 791 - Evaluating new solution: cost 781, does not meet the tolerances. + Optimization has finished. - Neighborhood search complete. - Maximum number of iterations completed. + Fixed-point implementation that met the tolerances found. - Total cost: 791 - Maximum absolute difference: 53.582715 - Use the explore method of the result to explore the implementation.
Проверьте точность модели после преобразования путем симуляции модели
sim_out = sim(model, 'SaveFormat', 'Dataset');
Постройте точность регрессии модели фиксированной точки.
plotRegression(sim_out, baseline_output, system_under_design, 'Regression after conversion');
Функция Активации Tanh в Слое 1 может быть заменена или интерполяционной таблицей или реализацией CORDIC для более эффективной генерации фиксированной точки. В этом примере мы будем использовать Оптимизатор Интерполяционной таблицы, чтобы получить интерполяционную таблицу как замену для tanh
. Мы будем использовать EvenPow2Spacing
для более быстрой скорости выполнения. Для получения дополнительной информации см. https://www.mathworks.com/help/fixedpoint/ref/functionapproximation.options-class.html.
block_path = [system_under_design '/Layer 1/tansig']; p = FunctionApproximation.Problem(block_path); p.Options.WordLengths = 8:32; p.Options.BreakpointSpecification = 'EvenPow2Spacing'; solution = p.solve; solution.replaceWithApproximate;
| ID | Memory (bits) | Feasible | Table Size | Breakpoints WLs | TableData WL | BreakpointSpecification | Error(Max,Current) | | 0 | 46 | 0 | 2 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 1 | 62 | 0 | 4 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 2 | 48 | 0 | 4 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 3 | 94 | 0 | 8 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 4 | 80 | 0 | 8 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 5 | 158 | 0 | 16 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 6 | 144 | 0 | 16 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 7 | 286 | 0 | 32 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 8 | 272 | 0 | 32 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 9 | 542 | 0 | 64 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 2.807617e-01 | | 10 | 528 | 0 | 64 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 2.807617e-01 | | 11 | 1054 | 0 | 128 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 8.007812e-02 | | 12 | 1040 | 0 | 128 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 8.007812e-02 | | 13 | 2078 | 0 | 256 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 1.855469e-02 | | 14 | 2064 | 0 | 256 | 8 | 8 | EvenPow2Spacing | 7.812500e-03, 1.855469e-02 | | 15 | 4126 | 1 | 512 | 15 | 8 | EvenPow2Spacing | 7.812500e-03, 7.812500e-03 | | 16 | 4114 | 1 | 512 | 9 | 8 | EvenPow2Spacing | 7.812500e-03, 7.812500e-03 | | 17 | 48 | 0 | 2 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 18 | 66 | 0 | 4 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 19 | 102 | 0 | 8 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 20 | 174 | 0 | 16 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 21 | 318 | 0 | 32 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 22 | 606 | 0 | 64 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 2.841797e-01 | | 23 | 592 | 0 | 64 | 8 | 9 | EvenPow2Spacing | 7.812500e-03, 2.841797e-01 | | 24 | 1182 | 0 | 128 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 8.349609e-02 | | 25 | 1168 | 0 | 128 | 8 | 9 | EvenPow2Spacing | 7.812500e-03, 8.349609e-02 | | 26 | 2334 | 0 | 256 | 15 | 9 | EvenPow2Spacing | 7.812500e-03, 2.587891e-02 | | 27 | 2320 | 0 | 256 | 8 | 9 | EvenPow2Spacing | 7.812500e-03, 2.587891e-02 | | 28 | 50 | 0 | 2 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 29 | 70 | 0 | 4 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 30 | 110 | 0 | 8 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 31 | 190 | 0 | 16 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 32 | 350 | 0 | 32 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 33 | 670 | 0 | 64 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 34 | 656 | 0 | 64 | 8 | 10 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 35 | 1310 | 0 | 128 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 36 | 1296 | 0 | 128 | 8 | 10 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 37 | 2590 | 0 | 256 | 15 | 10 | EvenPow2Spacing | 7.812500e-03, 2.441406e-02 | | 38 | 2576 | 0 | 256 | 8 | 10 | EvenPow2Spacing | 7.812500e-03, 2.441406e-02 | | 39 | 52 | 0 | 2 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 40 | 74 | 0 | 4 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 41 | 118 | 0 | 8 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 42 | 206 | 0 | 16 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 43 | 382 | 0 | 32 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 44 | 734 | 0 | 64 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 45 | 1438 | 0 | 128 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 46 | 1424 | 0 | 128 | 8 | 11 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 47 | 2846 | 0 | 256 | 15 | 11 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | | 48 | 2832 | 0 | 256 | 8 | 11 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | | 49 | 54 | 0 | 2 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 50 | 78 | 0 | 4 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 51 | 126 | 0 | 8 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 52 | 222 | 0 | 16 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 53 | 414 | 0 | 32 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 54 | 400 | 0 | 32 | 8 | 12 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 55 | 798 | 0 | 64 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 56 | 784 | 0 | 64 | 8 | 12 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 57 | 1566 | 0 | 128 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 58 | 1552 | 0 | 128 | 8 | 12 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 59 | 3102 | 0 | 256 | 15 | 12 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | | 60 | 3088 | 0 | 256 | 8 | 12 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | | 61 | 56 | 0 | 2 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 1.000000e+00 | | 62 | 82 | 0 | 4 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 9.091797e-01 | | 63 | 134 | 0 | 8 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 64 | 120 | 0 | 8 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 8.398438e-01 | | 65 | 238 | 0 | 16 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 66 | 224 | 0 | 16 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 7.231445e-01 | | 67 | 446 | 0 | 32 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 68 | 432 | 0 | 32 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 5.371094e-01 | | 69 | 862 | 0 | 64 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 70 | 848 | 0 | 64 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 2.827148e-01 | | 71 | 1694 | 0 | 128 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 72 | 1680 | 0 | 128 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 8.203125e-02 | | 73 | 3358 | 0 | 256 | 15 | 13 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | | 74 | 3344 | 0 | 256 | 8 | 13 | EvenPow2Spacing | 7.812500e-03, 2.343750e-02 | Best Solution | ID | Memory (bits) | Feasible | Table Size | Breakpoints WLs | TableData WL | BreakpointSpecification | Error(Max,Current) | | 16 | 4114 | 1 | 512 | 9 | 8 | EvenPow2Spacing | 7.812500e-03, 7.812500e-03 |
Проверьте точность модели после функциональной замены
sim_out = sim(model, 'SaveFormat', 'Dataset');
Постройте точность регрессии после функциональной замены
plotRegression(sim_out, baseline_output, system_under_design, 'Regression after function replacement');
Генерация HDL-кода требует лицензии HDL Coder™.
Выберите модель, для которой можно сгенерировать HDL-код и испытательный стенд.
systemname = 'fxpdemo_neuralnet_regression_toconvert/Function Fitting Neural Network';
Используйте временную директорию для сгенерированных файлов.
workingdir = tempname;
Можно запустить следующую команду, чтобы проверять на совместимость генерации HDL-кода.
checkhdl(systemname,'TargetDirectory',workingdir);
Запустите следующую команду, чтобы сгенерировать HDL-код.
makehdl(systemname,'TargetDirectory',workingdir);
Запустите следующую команду, чтобы сгенерировать испытательный стенд.
makehdltb(systemname,'TargetDirectory',workingdir);
close all; Simulink.sdi.close; clear engineInputs engineTargets net x t clear h1 h2 h3 clear sim_out logsout nn_out yarr_out ypred actual clear solution opts p close_system(model, 0); close_system(sysName, 0); clear system_under_design model block_path clear netName sysName clear best_solution baseline_output cd(current_dir); status = rmdir(fxpnn_temp_dir, 's'); %#ok clear fxpnn_demo_dir fxpnn_temp_dir current_dir status
Создайте функцию, чтобы отобразить данные о регрессии на графике
function plotRegression(sim_out, baseline_path, neural_network_output_path, plotTitle) nn_out = find(sim_out.logsout, 'BlockPath', neural_network_output_path); yarr_out = find(sim_out.logsout, 'BlockPath', baseline_path); ypred = nn_out{1}.Values.Data; actual = yarr_out{1}.Values.Data; figure; plotregression(double(ypred), actual, plotTitle); end