【问题标题】:Matlab Nested Classes, Reference to object of the same class from withinMatlab嵌套类,从内部引用同一类的对象
【发布时间】:2014-05-18 12:45:17
【问题描述】:

我正在尝试在 matlab 中创建一个树类来创建决策树。当我尝试运行这个脚本时,它第一次运行代码时,我可以看到它到达了一个有利的值 F 和 V。但是,在初始化左右新节点的部分之后,即使我的当前对象为空。如何在类中正确嵌套对同一类的引用,使它们不会相互干扰

classdef dtree
properties (Access = public) 
    MaxDepth;
    CurrentDepth;
    Features;
    Left;
    Right;
    F;
    V;
end
  methods
      function this=dtree(md, cd, nf, Xtrain, Ytrain)
        % Now the real initialization begins
        this.MaxDepth = md
        this.CurrentDepth = cd;
        this.Features = nf;
        this.train(Xtrain, Ytrain);
      end

      function s = gini(dt, Labels)
        s = 1;
        s = s - (sum(Labels > 0.0) ./ numel(Labels)) ^ 2;
        s = s - (sum(Labels < 0.0) ./ numel(Labels)) ^ 2;
    end

    function train(dt, Xtrain, Ytrain)
        if (size(unique(Ytrain)) == 1 | dt.CurrentDepth > dt.MaxDepth)
            return;
        end

        minGINI = Inf;
        minF = 0;
        minV = Inf;
        for i = dt.Features
            for n = 1:size(Xtrain, 1)
                idx = Xtrain(:, i) > Xtrain(n, i);
                GINI = dt.gini(Ytrain(idx)) + dt.gini(Ytrain(~idx));
                if GINI < minGINI
                    minGINI = GINI;
                    minF = i;
                    minV = Xtrain(n, i);
                end
            end
        end
        dt.F = minF
        dt.V = minV
        lIdx = Xtrain(:, dt.F) > Xtrain(dt.V, dt.F);
        dt.Left = dtree(dt.MaxDepth, dt.CurrentDepth + 1, dt.Features,Xtrain(lIdx, :), Ytrain(lIdx))
        dt.Right = dtree(dt.MaxDepth, dt.CurrentDepth + 1, dt.Features, Xtrain(~lIdx, :), Ytrain(~lIdx));
     end
  end

结束

ans = dtree(1, 1, [2, 5 ,6], XTrain, YTrain);

在执行过程中, 具有属性的 dtree:

    MaxDepth: 1
CurrentDepth: 1
    Features: [4 5 2]
        Left: []
       Right: []
           F: 5
           V: 7

执行后,当我输入 ans 答案 =

具有属性的dtree:

    MaxDepth: 1
CurrentDepth: 1
    Features: [4 5 2]
        Left: []
       Right: []
           F: []
           V: []

在运行火车之前这是一个空对象。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    在处理类方法时,需要显式地传递和返回对象

    function this = dtree(...)
       this = this.train(...)
    end
    
    function dt = train(dt, XTrain, YTrain)
    ...
    end
    

    如果你不这样做,你拥有的对象的引用将不会被更新。您总是需要在 Matlab 中更新引用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-11
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      相关资源
      最近更新 更多