c#与matlab混合编程 调用机器学习工具箱 决策树

时间:2024-04-03 15:46:43

首先是在 matlab 中训练模型,代码如下

clear all;
clc;

%加载训练  测试数据

y_valid = load('shuju/valid_data_label4.mat');
y_valid = y_valid.valid_data_label4;
x_valid = load('valid_data4.mat');
x_valid = x_valid.valid_data4;

x_train = load('train_data4.mat');
x_train = x_train.train_data4;
y_train = load('train_data_label4.mat');
y_train = y_train.train_data_label4;

%建立决策树 训练得到 模型:ctree

ctree = ClassificationTree.fit(x_train,y_train)

%剪枝

ctree = prune(ctree,'level',20);

%画图

view(ctree,'mode','graph');

%测试结果

    y_hat = predict(ctree,x_valid);
    acc_test = sum(y_hat == y_valid)/length(y_valid);
    disp(['测试准确度:' num2str(acc_test)])
    
    y_train_hat = predict(ctree,x_train);
    acc_train = sum(y_train_hat == y_train)/length(y_train);
    disp(['训练准确度:' num2str(acc_train)])

接下来是 main函数    

加载训练好的模型ctree

ctree = load('ctree.mat');
ctree = ctree.ctree;
Sg = importdata('E:\调制识别数据\IQ_2018-4-8新一批数据\WFM\WFM(97.4)\04-02-18 09h52m14s.csv');
Fs = 625000;
N = 65535;
modutype = zeros(1,200);
for ind = 1 :1: 200
    %截取信号段  长度为N
    start = floor(rand()*(length(Sg) - N));
    Isg = Sg(start : N + start, 1);
    Qsg = Sg(start : N + start, 2);
    %调制识别
    str = 'ctree.mat';
    modutype(ind) = MR_DT(Isg, Qsg, Fs, str);
    modutype(ind)
end

 

接下来是  函数 MR_DT

c#与matlab混合编程 调用机器学习工具箱 决策树

最主要的就是要加上以下两句  主要的作用就是将 训练的模型 ctree 正确的加载进来,如果不加这两句代码 不能正确加载ctree 成为一个ClassificationTree 的类  

%# function ClassificationTree
 % function MR_DT

详见http://ww2.mathworks.cn/help/compiler/function.html

下面的工作就是用deploytool 工具将 MR_DT 打包成 dll文件  供 c# 调用