Example: |
The following code shows a simple example how to train a random decision forest. It takes the first three columns (constant NXVARS) as the independent variables and the 12th column (constant TARGETCOL) as the y variable for the model. After training the random forest model the estimated y values are stored in an extra column appended to the data matrix:
program RFRegression;
const
NXVARS = 11;
TARGETCOL = 13;
var
RF : TRndForest;
i : integer;
LastC : integer;
obj : integer;
begin
RF := TRndForest.Create(nil); // create random forest model
RF.NTrees := 70; // set the parameters
RF.RPar := 0.65;
RF.ResizeTrnData (NXVARS, DStore.NrOfRows); // resize the trainíng data matrices
for i:=1 to NXVARS do // and fill them
RF.TrnDataX.CopyColumnFrom (DStore,i,i); // X data block
for obj:=1 to DStore.NrOfRows do
RF.TrnDataY[obj] := DStore.Elem[TARGETCOL,obj]; // Y data
RF.TrainRF; // perform the training
DStore.NrOfColumns := DStore.NrOfColumns + 1; // extend data matrix by one column
LastC := DStore.NrOfColumns;
DStore.ColName[LastC] := 'Estimated';
for obj:=1 to DStore.NrOfRows do // copy estimated values into last column
DStore.Elem[LastC,obj] := RF.YHat[obj];
RF.SaveOnDisk (GetDLabDir(ddWork)+'test_rf', true);// save trained random forest
RF.Free;
end.
|