[11217] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using ExcelDna.Integration;
|
---|
| 5 | using HeuristicLab.Problems.DataAnalysis;
|
---|
| 6 |
|
---|
| 7 | namespace HeuristicLabExcel {
|
---|
| 8 |
|
---|
| 9 | public class ExcelFunctions {
|
---|
| 10 | /* Standard example from ExcelDNA */
|
---|
| 11 | [ExcelFunction(Description = "Multiplies two numbers", Category = "Useful functions")]
|
---|
| 12 | public static double MultiplyThem(double x, double y) {
|
---|
| 13 | return x * y;
|
---|
| 14 | }
|
---|
| 15 | [ExcelFunction(Description = "Random forest", Category = "Useful functions")]
|
---|
| 16 | public static double[,] PredictRandomForest(double[,] x, double[] y) {
|
---|
| 17 | int nRows = x.GetLength(0);
|
---|
| 18 | int nCols = x.GetLength(1);
|
---|
| 19 | if (nRows > 5000) throw new ArgumentException("y");
|
---|
| 20 | if (nCols >= nRows) throw new ArgumentException("x");
|
---|
| 21 | var inputs = Enumerable.Range(0, nCols).Select(i => "x" + i);
|
---|
| 22 | var target = "y";
|
---|
| 23 | var variables = inputs.Concat(new string[] { target });
|
---|
| 24 | // copy data
|
---|
| 25 | var xy = new double[nRows, nCols + 1];
|
---|
| 26 | for (int r = 0; r < nRows; r++) {
|
---|
| 27 | for (int c = 0; c < nCols; c++) {
|
---|
| 28 | xy[r, c] = x[r, c];
|
---|
| 29 | }
|
---|
| 30 | if (r < y.Length)
|
---|
| 31 | xy[r, nCols] = y[r];
|
---|
| 32 | }
|
---|
| 33 | var ds = new Dataset(variables, xy);
|
---|
| 34 |
|
---|
| 35 | var problemData = new RegressionProblemData(ds, inputs, target);
|
---|
| 36 | problemData.TrainingPartition.Start = 0;
|
---|
| 37 | problemData.TrainingPartition.End = y.Length;
|
---|
| 38 | problemData.TestPartition.Start = y.Length;
|
---|
| 39 | problemData.TestPartition.End = nRows;
|
---|
| 40 |
|
---|
| 41 | double rmsError;
|
---|
| 42 | double oobAvgRelError;
|
---|
| 43 | double oobRmsError;
|
---|
| 44 | double avgRelError;
|
---|
| 45 | var rf = HeuristicLab.Algorithms.DataAnalysis.RandomForestRegression.CreateRandomForestRegressionSolution(problemData, 100, 0.5, 0.5, 31415, out rmsError, out avgRelError, out oobRmsError, out oobAvgRelError);
|
---|
| 46 |
|
---|
| 47 | // copy for output
|
---|
| 48 | var res = new double[nRows, 1];
|
---|
| 49 | var estValuesEnum = rf.EstimatedValues.GetEnumerator();
|
---|
| 50 | estValuesEnum.MoveNext();
|
---|
| 51 | for (int r = 0; r < nRows; r++) {
|
---|
| 52 | res[r, 0] = estValuesEnum.Current;
|
---|
| 53 | estValuesEnum.MoveNext();
|
---|
| 54 | }
|
---|
| 55 | return res;
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 | }
|
---|