Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Microsoft.ML.Core/Prediction/ITrainer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,8 @@ public interface IModelCombiner<TModel, TPredictor>
TPredictor CombineModels(IEnumerable<TModel> models);
}

public delegate void SignatureModelCombiner(PredictionKind kind);

/// <summary>
/// Weakly typed interface for a trainer "session" that produces a predictor.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.ML.FastTree/Microsoft.ML.FastTree.csproj
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<Compile Include="TreeEnsemble\Ensemble.cs" />
<Compile Include="TreeEnsemble\QuantileRegressionTree.cs" />
<Compile Include="TreeEnsemble\RegressionTree.cs" />
<Compile Include="TreeEnsemble\TreeEnsembleCombiner.cs" />
<Compile Include="Training\Applications\GradientWrappers.cs" />
<Compile Include="Training\Applications\ObjectiveFunction.cs" />
<Compile Include="Training\BaggingProvider.cs" />
Expand Down
49 changes: 33 additions & 16 deletions src/Microsoft.ML.FastTree/TreeEnsemble/RegressionTree.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -105,22 +105,21 @@ public RegressionTree(byte[] buffer, ref int position)
LteChild = buffer.ToIntArray(ref position);
GtChild = buffer.ToIntArray(ref position);
SplitFeatures = buffer.ToIntArray(ref position);
int[] categoricalNodeIndices = buffer.ToIntArray(ref position);
CategoricalSplit = GetCategoricalSplitFromIndices(categoricalNodeIndices);
if (categoricalNodeIndices?.Length > 0)
byte[] categoricalSplitAsBytes = buffer.ToByteArray(ref position);
CategoricalSplit = categoricalSplitAsBytes.Select(b => b > 0).ToArray();
if (CategoricalSplit.Any(b => b))

@codemzscodemzsJun 15, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing this. We should add a test for this function. I believe this function is not used when saving the tree model to disk and reading it back in TrainTest or CV, hence it was not caught during testing. #Resolved

{
CategoricalSplitFeatures = new int[NumNodes][];
CategoricalSplitFeatureRanges = new int[NumNodes][];
foreach (var index in categoricalNodeIndices)
for (int index = 0; index < NumNodes; index++)
{
Contracts.Assert(CategoricalSplit[index]);

CategoricalSplitFeatures[index] = buffer.ToIntArray(ref position);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position, 2);
CategoricalSplitFeatureRanges[index] = buffer.ToIntArray(ref position);
}
}

Thresholds = buffer.ToUIntArray(ref position);
RawThresholds = buffer.ToFloatArray(ref position);
_splitGain = buffer.ToDoubleArray(ref position);
_gainPValue = buffer.ToDoubleArray(ref position);
_previousLeafValue = buffer.ToDoubleArray(ref position);
Expand All@@ -144,6 +143,23 @@ private bool[] GetCategoricalSplitFromIndices(int[] indices)
return categoricalSplit;
}

private bool[] GetCategoricalSplitFromBytes(byte[] indices)
{
bool[] categoricalSplit = new bool[NumNodes];
if (indices == null)
return categoricalSplit;

Contracts.Assert(indices.Length <= NumNodes);

foreach (int index in indices)
{
Contracts.Assert(index >= 0 && index < NumNodes);
categoricalSplit[index] = true;
}

return categoricalSplit;
}

/// <summary>
/// Create a Regression Tree object from raw tree contents.
/// </summary>
Expand DownExpand Up@@ -192,7 +208,7 @@ internal RegressionTree(int[] splitFeatures, Double[] splitGain, Double[] gainPV
LeafValues = leafValues;
CategoricalSplitFeatures = categoricalSplitFeatures;
CategoricalSplitFeatureRanges = new int[CategoricalSplitFeatures.Length][];
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
for(int i= 0; i < CategoricalSplitFeatures.Length; ++i)
{
if (CategoricalSplitFeatures[i] != null && CategoricalSplitFeatures[i].Length > 0)
{
Expand DownExpand Up@@ -500,6 +516,7 @@ public virtual int SizeInBytes()
NumNodes * sizeof(int) +
CategoricalSplit.Length * sizeof(bool) +
Thresholds.SizeInBytes() +
RawThresholds.SizeInBytes() +
_splitGain.SizeInBytes() +
_gainPValue.SizeInBytes() +
_previousLeafValue.SizeInBytes() +
Expand All@@ -514,22 +531,22 @@ public virtual void ToByteArray(byte[] buffer, ref int position)
LteChild.ToByteArray(buffer, ref position);
GtChild.ToByteArray(buffer, ref position);
SplitFeatures.ToByteArray(buffer, ref position);
CategoricalSplit.Length.ToByteArray(buffer, ref position);
foreach (var split in CategoricalSplit)
Convert.ToByte(split).ToByteArray(buffer, ref position);

if (CategoricalSplitFeatures != null)
{
foreach (var splits in CategoricalSplitFeatures)
splits.ToByteArray(buffer, ref position);
}

if (CategoricalSplitFeatureRanges != null)
{
foreach (var ranges in CategoricalSplitFeatureRanges)
ranges.ToByteArray(buffer, ref position);
Contracts.AssertValue(CategoricalSplitFeatureRanges);
for (int i = 0; i < CategoricalSplitFeatures.Length; i++)
{
CategoricalSplitFeatures[i].ToByteArray(buffer, ref position);
CategoricalSplitFeatureRanges[i].ToByteArray(buffer, ref position);
}
}

Thresholds.ToByteArray(buffer, ref position);
RawThresholds.ToByteArray(buffer, ref position);
_splitGain.ToByteArray(buffer, ref position);
_gainPValue.ToByteArray(buffer, ref position);
_previousLeafValue.ToByteArray(buffer, ref position);
Expand Down
115 changes: 115 additions & 0 deletions src/Microsoft.ML.FastTree/TreeEnsemble/TreeEnsembleCombiner.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Calibration;

[assembly: LoadableClass(typeof(TreeEnsembleCombiner), null, typeof(SignatureModelCombiner), "Fast Tree Model Combiner", "FastTreeCombiner")]

namespace Microsoft.ML.Runtime.FastTree.Internal
{
public sealed class TreeEnsembleCombiner : IModelCombiner<IPredictorProducing<float>, IPredictorProducing<float>>
{
private readonly IHost _host;
private readonly PredictionKind _kind;

public TreeEnsembleCombiner(IHostEnvironment env, PredictionKind kind)
{
_host = env.Register("TreeEnsembleCombiner");
switch (kind)
{
case PredictionKind.BinaryClassification:
case PredictionKind.Regression:
case PredictionKind.Ranking:
_kind = kind;
break;
default:
throw _host.ExceptUserArg(nameof(kind), $"Tree ensembles can be either of type {nameof(PredictionKind.BinaryClassification)}, " +
$"{nameof(PredictionKind.Regression)} or {nameof(PredictionKind.Ranking)}");
}
}

public IPredictorProducing<float> CombineModels(IEnumerable<IPredictorProducing<float>> models)
{
_host.CheckValue(models, nameof(models));

var ensemble = new Ensemble();
int modelCount = 0;
int featureCount = -1;
bool binaryClassifier = false;
foreach (var model in models)
{
modelCount++;

var predictor = model;
_host.CheckValue(predictor, nameof(models), "One of the models is null");

var calibrated = predictor as CalibratedPredictorBase;
double paramA = 1;
if (calibrated != null)
{
_host.Check(calibrated.Calibrator is PlattCalibrator,
"Combining FastTree models can only be done when the models are calibrated with Platt calibrator");
predictor = calibrated.SubPredictor;
paramA = -(calibrated.Calibrator as PlattCalibrator).ParamA;
}
var tree = predictor as FastTreePredictionWrapper;
if (tree == null)
throw _host.Except("Model is not a tree ensemble");
foreach (var t in tree.TrainedEnsemble.Trees)
{
var bytes = new byte[t.SizeInBytes()];
int position = -1;
t.ToByteArray(bytes, ref position);
position = -1;
var tNew = new RegressionTree(bytes, ref position);
if (paramA != 1)
{
for (int i = 0; i < tNew.NumLeaves; i++)
tNew.SetOutput(i, tNew.LeafValues[i] * paramA);
}
ensemble.AddTree(tNew);
}

if (modelCount == 1)
{
binaryClassifier = calibrated != null;
featureCount = tree.InputType.ValueCount;
}
else
{
_host.Check((calibrated != null) == binaryClassifier, "Ensemble contains both calibrated and uncalibrated models");
_host.Check(featureCount == tree.InputType.ValueCount, "Found models with different number of features");
}
}

var scale = 1 / (double)modelCount;

foreach (var t in ensemble.Trees)
{
for (int i = 0; i < t.NumLeaves; i++)
t.SetOutput(i, t.LeafValues[i] * scale);
}

switch (_kind)
{
case PredictionKind.BinaryClassification:
if (!binaryClassifier)
return new FastTreeBinaryPredictor(_host, ensemble, featureCount, null);

var cali = new PlattCalibrator(_host, -1, 0);
return new FeatureWeightsCalibratedPredictor(_host, new FastTreeBinaryPredictor(_host, ensemble, featureCount, null), cali);
case PredictionKind.Regression:
return new FastTreeRegressionPredictor(_host, ensemble, featureCount, null);
case PredictionKind.Ranking:
return new FastTreeRankingPredictor(_host, ensemble, featureCount, null);
default:
_host.Assert(false);
throw _host.ExceptNotSupp();
}
}
}
}
34 changes: 20 additions & 14 deletions src/Microsoft.ML.FastTree/Utils/ToByteArrayExtensions.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime.Internal.Utilities;

namespace Microsoft.ML.Runtime.FastTree.Internal
{
Expand DownExpand Up@@ -290,7 +291,7 @@ public static string ToString(this byte[] buffer, ref int position)

public static int SizeInBytes(this byte[] a)
{
return sizeof(int) + a.Length * sizeof(byte);
return sizeof(int) + Utils.Size(a) * sizeof(byte);
}

public static void ToByteArray(this byte[] a, byte[] buffer, ref int position)
Expand All@@ -314,7 +315,7 @@ public static byte[] ToByteArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this short[] a)
{
return sizeof(int) + a.Length * sizeof(short);
return sizeof(int) + Utils.Size(a) * sizeof(short);
}

public unsafe static void ToByteArray(this short[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -353,7 +354,7 @@ public unsafe static short[] ToShortArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ushort[] a)
{
return sizeof(int) + a.Length * sizeof(ushort);
return sizeof(int) + Utils.Size(a) * sizeof(ushort);
}

public unsafe static void ToByteArray(this ushort[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -392,12 +393,12 @@ public unsafe static ushort[] ToUShortArray(this byte[] buffer, ref int position

public static int SizeInBytes(this int[] array)
{
return sizeof(int) + array.Length * sizeof(int);
return sizeof(int) + Utils.Size(array) * sizeof(int);
}

public unsafe static void ToByteArray(this int[] a, byte[] buffer, ref int position)
{
int length = a.Length;
int length = Utils.Size(a);
length.ToByteArray(buffer, ref position);

fixed (byte* tmpBuffer = buffer)
Expand All@@ -415,6 +416,9 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position)

public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int length)
{
if (length == 0)
return null;

int[] a = new int[length];

fixed (byte* tmpBuffer = buffer)
Expand All@@ -433,7 +437,7 @@ public unsafe static int[] ToIntArray(this byte[] buffer, ref int position, int

public static int SizeInBytes(this uint[] array)
{
return sizeof(int) + array.Length * sizeof(uint);
return sizeof(int) + Utils.Size(array) * sizeof(uint);
}

public unsafe static void ToByteArray(this uint[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -472,7 +476,7 @@ public unsafe static uint[] ToUIntArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this long[] array)
{
return sizeof(int) + array.Length * sizeof(long);
return sizeof(int) + Utils.Size(array) * sizeof(long);
}

public unsafe static void ToByteArray(this long[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -511,7 +515,7 @@ public unsafe static long[] ToLongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this ulong[] array)
{
return sizeof(int) + array.Length * sizeof(ulong);
return sizeof(int) + Utils.Size(array) * sizeof(ulong);
}

public unsafe static void ToByteArray(this ulong[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -550,7 +554,7 @@ public unsafe static ulong[] ToULongArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this MD5Hash[] array)
{
return sizeof(int) + array.Length * MD5Hash.SizeInBytes();
return sizeof(int) + Utils.Size(array) * MD5Hash.SizeInBytes();
}

public static void ToByteArray(this MD5Hash[] a, byte[] buffer, ref int position)
Expand All@@ -577,7 +581,7 @@ public unsafe static MD5Hash[] ToUInt128Array(this byte[] buffer, ref int positi

public static int SizeInBytes(this float[] array)
{
return sizeof(int) + array.Length * sizeof(float);
return sizeof(int) + Utils.Size(array) * sizeof(float);
}

public unsafe static void ToByteArray(this float[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -616,7 +620,7 @@ public unsafe static float[] ToFloatArray(this byte[] buffer, ref int position)

public static int SizeInBytes(this double[] array)
{
return sizeof(int) + array.Length * sizeof(double);
return sizeof(int) + Utils.Size(array) * sizeof(double);
}

public unsafe static void ToByteArray(this double[] a, byte[] buffer, ref int position)
Expand DownExpand Up@@ -655,6 +659,8 @@ public unsafe static double[] ToDoubleArray(this byte[] buffer, ref int position

public static int SizeInBytes(this double[][] array)
{
if (Utils.Size(array) == 0)
return sizeof(int);
return sizeof(int) + array.Sum(x => x.SizeInBytes());
}

Expand DownExpand Up@@ -683,7 +689,7 @@ public static double[][] ToDoubleJaggedArray(this byte[] buffer, ref int positio
public static long SizeInBytes(this string[] array)
{
long length = sizeof(int);
for (int i = 0; i < array.Length; ++i)
for (int i = 0; i < Utils.Size(array); ++i)
{
length += array[i].SizeInBytes();
}
Expand All@@ -692,8 +698,8 @@ public static long SizeInBytes(this string[] array)

public static void ToByteArray(this string[] a, byte[] buffer, ref int position)
{
a.Length.ToByteArray(buffer, ref position);
for (int i = 0; i < a.Length; ++i)
Utils.Size(a).ToByteArray(buffer, ref position);
for (int i = 0; i < Utils.Size(a); ++i)
{
a[i].ToByteArray(buffer, ref position);
}
Expand Down
Loading