-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ExperimentBase.cs
344 lines (315 loc) · 19.6 KB
/
ExperimentBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// 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;
using System.Collections.Generic;
using Microsoft.ML.Data;
using Microsoft.ML.Runtime;
namespace Microsoft.ML.AutoML
{
/// <summary>
/// AutoML experiment base class. All task-specific AutoML experiments
/// (like <see cref="BinaryClassificationExperiment"/>) inherit from this class.
/// </summary>
/// <typeparam name="TMetrics">Metrics type used by task-specific AutoML experiments.</typeparam>
/// <typeparam name="TExperimentSettings">Experiment settings type.</typeparam>
public abstract class ExperimentBase<TMetrics, TExperimentSettings>
where TMetrics : class
where TExperimentSettings : ExperimentSettings
{
private protected readonly MLContext Context;
private protected readonly IMetricsAgent<TMetrics> MetricsAgent;
private protected readonly OptimizingMetricInfo OptimizingMetricInfo;
private protected readonly TExperimentSettings Settings;
private readonly IChannel _logger;
private readonly TaskKind _task;
private readonly IEnumerable<TrainerName> _trainerWhitelist;
internal ExperimentBase(MLContext context,
IMetricsAgent<TMetrics> metricsAgent,
OptimizingMetricInfo optimizingMetricInfo,
TExperimentSettings settings,
TaskKind task,
IEnumerable<TrainerName> trainerWhitelist)
{
Context = context;
MetricsAgent = metricsAgent;
OptimizingMetricInfo = optimizingMetricInfo;
Settings = settings;
_logger = ((IChannelProvider)context).Start("AutoML");
_task = task;
_trainerWhitelist = trainerWhitelist;
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data used by the AutoML experiment.</param>
/// <param name="labelColumnName">The dataset column used as the label.</param>
/// <param name="samplingKeyColumn">The dataset column used as the sampling key column.
/// See <see cref="ColumnInformation.SamplingKeyColumnName"/> for more information.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public ExperimentResult<TMetrics> Execute(IDataView trainData, string labelColumnName = DefaultColumnNames.Label,
string samplingKeyColumn = null, IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<TMetrics>> progressHandler = null)
{
var columnInformation = new ColumnInformation()
{
LabelColumnName = labelColumnName,
SamplingKeyColumnName = samplingKeyColumn
};
return Execute(trainData, columnInformation, preFeaturizer, progressHandler);
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data to be used by the AutoML experiment.</param>
/// <param name="columnInformation">Column information for the dataset.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public ExperimentResult<TMetrics> Execute(IDataView trainData, ColumnInformation columnInformation,
IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<TMetrics>> progressHandler = null)
{
// Cross val threshold for # of dataset rows --
// If dataset has < threshold # of rows, use cross val.
// Else, run experiment using train-validate split.
const int crossValRowCountThreshold = 15000;
var rowCount = DatasetDimensionsUtil.CountRows(trainData, crossValRowCountThreshold);
if (rowCount < crossValRowCountThreshold)
{
const int numCrossValFolds = 10;
var splitResult = SplitUtil.CrossValSplit(Context, trainData, numCrossValFolds, columnInformation?.SamplingKeyColumnName);
return ExecuteCrossValSummary(splitResult.trainDatasets, columnInformation, splitResult.validationDatasets, preFeaturizer, progressHandler);
}
else
{
var splitResult = SplitUtil.TrainValidateSplit(Context, trainData, columnInformation?.SamplingKeyColumnName);
return ExecuteTrainValidate(splitResult.trainData, columnInformation, splitResult.validationData, preFeaturizer, progressHandler);
}
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data to be used by the AutoML experiment.</param>
/// <param name="validationData">The validation data to be used by the AutoML experiment.</param>
/// <param name="labelColumnName">The name of the label column.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public ExperimentResult<TMetrics> Execute(IDataView trainData, IDataView validationData, string labelColumnName = DefaultColumnNames.Label, IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<TMetrics>> progressHandler = null)
{
var columnInformation = new ColumnInformation() { LabelColumnName = labelColumnName };
return Execute(trainData, validationData, columnInformation, preFeaturizer, progressHandler);
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data to be used by the AutoML experiment.</param>
/// <param name="validationData">The validation data to be used by the AutoML experiment.</param>
/// <param name="columnInformation">Column information for the dataset.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public ExperimentResult<TMetrics> Execute(IDataView trainData, IDataView validationData,
ColumnInformation columnInformation, IEstimator<ITransformer> preFeaturizer = null,
IProgress<RunDetail<TMetrics>> progressHandler = null)
{
if (validationData == null)
{
return Execute(trainData, columnInformation, preFeaturizer, progressHandler);
}
return ExecuteTrainValidate(trainData, columnInformation, validationData, preFeaturizer, progressHandler);
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data to be used by the AutoML experiment.</param>
/// <param name="numberOfCVFolds">The number of cross validation folds into which the training data should be divided when fitting a model.</param>
/// <param name="columnInformation">Column information for the dataset.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The cross validation experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public CrossValidationExperimentResult<TMetrics> Execute(IDataView trainData, uint numberOfCVFolds,
ColumnInformation columnInformation = null, IEstimator<ITransformer> preFeaturizer = null,
IProgress<CrossValidationRunDetail<TMetrics>> progressHandler = null)
{
UserInputValidationUtil.ValidateNumberOfCVFoldsArg(numberOfCVFolds);
var splitResult = SplitUtil.CrossValSplit(Context, trainData, numberOfCVFolds, columnInformation?.SamplingKeyColumnName);
return ExecuteCrossVal(splitResult.trainDatasets, columnInformation, splitResult.validationDatasets, preFeaturizer, progressHandler);
}
/// <summary>
/// Executes an AutoML experiment.
/// </summary>
/// <param name="trainData">The training data to be used by the AutoML experiment.</param>
/// <param name="numberOfCVFolds">The number of cross validation folds into which the training data should be divided when fitting a model.</param>
/// <param name="labelColumnName">The name of the label column.</param>
/// <param name="samplingKeyColumn">The name of the sampling key column.</param>
/// <param name="preFeaturizer">Pre-featurizer that AutoML will apply to the data during an
/// experiment. (The pre-featurizer will be fit only on the training data split to produce a
/// trained transform. Then, the trained transform will be applied to both the training
/// data split and corresponding validation data split.)</param>
/// <param name="progressHandler">A user-defined object that implements
/// the <see cref="IProgress{T}"/> interface. AutoML will invoke the method
/// <see cref="IProgress{T}.Report(T)"/> after each model it produces during the
/// course of the experiment.
/// </param>
/// <returns>The cross validation experiment result.</returns>
/// <remarks>
/// Depending on the size of your data, the AutoML experiment could take a long time to execute.
/// </remarks>
public CrossValidationExperimentResult<TMetrics> Execute(IDataView trainData,
uint numberOfCVFolds, string labelColumnName = DefaultColumnNames.Label,
string samplingKeyColumn = null, IEstimator<ITransformer> preFeaturizer = null,
Progress<CrossValidationRunDetail<TMetrics>> progressHandler = null)
{
var columnInformation = new ColumnInformation()
{
LabelColumnName = labelColumnName,
SamplingKeyColumnName = samplingKeyColumn
};
return Execute(trainData, numberOfCVFolds, columnInformation, preFeaturizer, progressHandler);
}
private protected abstract CrossValidationRunDetail<TMetrics> GetBestCrossValRun(IEnumerable<CrossValidationRunDetail<TMetrics>> results);
private protected abstract RunDetail<TMetrics> GetBestRun(IEnumerable<RunDetail<TMetrics>> results);
private ExperimentResult<TMetrics> ExecuteTrainValidate(IDataView trainData,
ColumnInformation columnInfo,
IDataView validationData,
IEstimator<ITransformer> preFeaturizer,
IProgress<RunDetail<TMetrics>> progressHandler)
{
columnInfo = columnInfo ?? new ColumnInformation();
UserInputValidationUtil.ValidateExperimentExecuteArgs(trainData, columnInfo, validationData, _task);
// Apply pre-featurizer
ITransformer preprocessorTransform = null;
if (preFeaturizer != null)
{
preprocessorTransform = preFeaturizer.Fit(trainData);
trainData = preprocessorTransform.Transform(trainData);
validationData = preprocessorTransform.Transform(validationData);
}
var runner = new TrainValidateRunner<TMetrics>(Context, trainData, validationData, columnInfo.LabelColumnName, MetricsAgent,
preFeaturizer, preprocessorTransform, _logger);
var columns = DatasetColumnInfoUtil.GetDatasetColumnInfo(Context, trainData, columnInfo);
return Execute(columnInfo, columns, preFeaturizer, progressHandler, runner);
}
private CrossValidationExperimentResult<TMetrics> ExecuteCrossVal(IDataView[] trainDatasets,
ColumnInformation columnInfo,
IDataView[] validationDatasets,
IEstimator<ITransformer> preFeaturizer,
IProgress<CrossValidationRunDetail<TMetrics>> progressHandler)
{
columnInfo = columnInfo ?? new ColumnInformation();
UserInputValidationUtil.ValidateExperimentExecuteArgs(trainDatasets[0], columnInfo, validationDatasets[0], _task);
// Apply pre-featurizer
ITransformer[] preprocessorTransforms = null;
(trainDatasets, validationDatasets, preprocessorTransforms) = ApplyPreFeaturizerCrossVal(trainDatasets, validationDatasets, preFeaturizer);
var runner = new CrossValRunner<TMetrics>(Context, trainDatasets, validationDatasets, MetricsAgent, preFeaturizer,
preprocessorTransforms, columnInfo.LabelColumnName, _logger);
var columns = DatasetColumnInfoUtil.GetDatasetColumnInfo(Context, trainDatasets[0], columnInfo);
// Execute experiment & get all pipelines run
var experiment = new Experiment<CrossValidationRunDetail<TMetrics>, TMetrics>(Context, _task, OptimizingMetricInfo, progressHandler,
Settings, MetricsAgent, _trainerWhitelist, columns, runner, _logger);
var runDetails = experiment.Execute();
var bestRun = GetBestCrossValRun(runDetails);
var experimentResult = new CrossValidationExperimentResult<TMetrics>(runDetails, bestRun);
return experimentResult;
}
private ExperimentResult<TMetrics> ExecuteCrossValSummary(IDataView[] trainDatasets,
ColumnInformation columnInfo,
IDataView[] validationDatasets,
IEstimator<ITransformer> preFeaturizer,
IProgress<RunDetail<TMetrics>> progressHandler)
{
columnInfo = columnInfo ?? new ColumnInformation();
UserInputValidationUtil.ValidateExperimentExecuteArgs(trainDatasets[0], columnInfo, validationDatasets[0], _task);
// Apply pre-featurizer
ITransformer[] preprocessorTransforms = null;
(trainDatasets, validationDatasets, preprocessorTransforms) = ApplyPreFeaturizerCrossVal(trainDatasets, validationDatasets, preFeaturizer);
var runner = new CrossValSummaryRunner<TMetrics>(Context, trainDatasets, validationDatasets, MetricsAgent, preFeaturizer,
preprocessorTransforms, columnInfo.LabelColumnName, OptimizingMetricInfo, _logger);
var columns = DatasetColumnInfoUtil.GetDatasetColumnInfo(Context, trainDatasets[0], columnInfo);
return Execute(columnInfo, columns, preFeaturizer, progressHandler, runner);
}
private ExperimentResult<TMetrics> Execute(ColumnInformation columnInfo,
DatasetColumnInfo[] columns,
IEstimator<ITransformer> preFeaturizer,
IProgress<RunDetail<TMetrics>> progressHandler,
IRunner<RunDetail<TMetrics>> runner)
{
// Execute experiment & get all pipelines run
var experiment = new Experiment<RunDetail<TMetrics>, TMetrics>(Context, _task, OptimizingMetricInfo, progressHandler,
Settings, MetricsAgent, _trainerWhitelist, columns, runner, _logger);
var runDetails = experiment.Execute();
var bestRun = GetBestRun(runDetails);
var experimentResult = new ExperimentResult<TMetrics>(runDetails, bestRun);
return experimentResult;
}
private static (IDataView[] trainDatasets, IDataView[] validDatasets, ITransformer[] preprocessorTransforms)
ApplyPreFeaturizerCrossVal(IDataView[] trainDatasets, IDataView[] validDatasets, IEstimator<ITransformer> preFeaturizer)
{
if (preFeaturizer == null)
{
return (trainDatasets, validDatasets, null);
}
var preprocessorTransforms = new ITransformer[trainDatasets.Length];
for (var i = 0; i < trainDatasets.Length; i++)
{
// Preprocess train and validation data
preprocessorTransforms[i] = preFeaturizer.Fit(trainDatasets[i]);
trainDatasets[i] = preprocessorTransforms[i].Transform(trainDatasets[i]);
validDatasets[i] = preprocessorTransforms[i].Transform(validDatasets[i]);
}
return (trainDatasets, validDatasets, preprocessorTransforms);
}
}
}