Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
16 changes: 12 additions & 4 deletions src/Microsoft.ML.Core/Utilities/DoubleParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ internal static class DoubleParser
private const ulong TopThreeBits = 0xE000000000000000UL;
private const char InfinitySymbol = '\u221E';

// The decimal marker that separates the integer part from the fractional part of a number
// written in decimal from can vary across different cultures as either '.' or ','. The
// default decimal marker in ML .NET is '.', however through this static char variable,
// we allow users to specify the decimal marker used in their datasets as ',' as well.
[BestFriend]
internal static char DecimalMarker = '.';

Comment thread
mstfbl marked this conversation as resolved.
// REVIEW: casting ulong to Double doesn't always do the right thing, for example
// with 0x84595161401484A0UL. Hence the gymnastics several places in this code. Note that
// long to Double does work. The work around is:
Expand Down Expand Up @@ -555,6 +562,7 @@ private static bool TryParseCore(ReadOnlySpan<char> span, ref int ich, ref bool
break;

case '.':
case ',':
goto LPoint;
Comment thread
mstfbl marked this conversation as resolved.

// The common cases.
Expand All @@ -571,7 +579,7 @@ private static bool TryParseCore(ReadOnlySpan<char> span, ref int ich, ref bool
break;
}

// Get digits before '.'
// Get digits before the decimal marker, which may be '.' or ','
uint d;
for (; ; )
{
Expand All @@ -593,14 +601,14 @@ private static bool TryParseCore(ReadOnlySpan<char> span, ref int ich, ref bool
}
Contracts.Assert(i < span.Length);

if (span[i] != '.')
if (span[i] != DecimalMarker)
goto LAfterDigits;

LPoint:
Contracts.Assert(i < span.Length);
Contracts.Assert(span[i] == '.');
Contracts.Assert(span[i] == DecimalMarker);

// Get the digits after '.'
// Get the digits after the decimal marker, which may be '.' or ','
for (; ; )
{
if (++i >= span.Length)
Expand Down
26 changes: 25 additions & 1 deletion src/Microsoft.ML.Data/DataLoadSave/Text/TextLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,12 @@ public class Options
[Argument(ArgumentType.AtMostOnce, Name = nameof(Separator), Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly, HelpText = "Source column separator.", ShortName = "sep")]
public char[] Separators = new[] { Defaults.Separator };

/// <summary>
/// The character that should be used as the decimal marker.
/// </summary>
[Argument(ArgumentType.AtMostOnce, Name = "Decimal Marker", HelpText = "Character symbol used to separate the integer part from the fractional part of a number written in decimal form.", ShortName = "decimal")]
public char DecimalMarker = Defaults.DecimalMarker;
Comment thread
mstfbl marked this conversation as resolved.
Comment thread
mstfbl marked this conversation as resolved.

/// <summary>
/// Specifies the input columns that should be mapped to <see cref="IDataView"/> columns.
/// </summary>
Expand Down Expand Up @@ -535,6 +541,7 @@ internal static class Defaults
internal const bool AllowQuoting = false;
internal const bool AllowSparse = false;
internal const char Separator = '\t';
internal const char DecimalMarker = '.';
internal const bool HasHeader = false;
internal const bool TrimWhitespace = false;
internal const bool ReadMultilines = false;
Expand Down Expand Up @@ -1063,7 +1070,8 @@ private static VersionInfo GetVersionInfo()
// verWrittenCur: 0x00010009, // Introduced _flags
//verWrittenCur: 0x0001000A, // Added ForceVector in Range
//verWrittenCur: 0x0001000B, // Header now retained if used and present
verWrittenCur: 0x0001000C, // Removed Min and Contiguous from KeyType, and added ReadMultilines flag to OptionFlags
//verWrittenCur: 0x0001000C, // Removed Min and Contiguous from KeyType, and added ReadMultilines flag to OptionFlags
verWrittenCur: 0x0001000D, // Added decimal marker option to allow for ',' to be a decimal marker
Comment thread
mstfbl marked this conversation as resolved.
Outdated
verReadableCur: 0x0001000A,
verWeCanReadBack: 0x00010009,
loaderSignature: LoaderSignature,
Expand Down Expand Up @@ -1094,6 +1102,7 @@ private enum OptionFlags : uint
// Input size is zero for unknown - determined by the data (including sparse rows).
private readonly int _inputSize;
private readonly char[] _separators;
private readonly char _decimalMarker;
private readonly Bindings _bindings;

private readonly Parser _parser;
Expand Down Expand Up @@ -1210,6 +1219,11 @@ internal TextLoader(IHostEnvironment env, Options options = null, IMultiStreamSo
}
}

if (options.DecimalMarker != '.' && options.DecimalMarker != ',')
throw _host.ExceptUserArg(nameof(Options.DecimalMarker), "Decimal marker cannot be the '{0}' character. It must be '.' or ','.", options.DecimalMarker);
if (_separators.Contains(options.DecimalMarker))
throw _host.ExceptUserArg(nameof(Options.DecimalMarker), "Decimal marker and separator cannot be the same '{0}' character.", options.DecimalMarker);
_decimalMarker = options.DecimalMarker;
Comment thread
mstfbl marked this conversation as resolved.
_bindings = new Bindings(this, cols, headerFile, dataSample);
_parser = new Parser(this);
}
Expand Down Expand Up @@ -1373,6 +1387,7 @@ private TextLoader(IHost host, ModelLoadContext ctx)
// int: inputSize: 0 for determined from data
// int: number of separators
// char[]: separators
// char: decimal marker
// bindings
int cbFloat = ctx.Reader.ReadInt32();
host.CheckDecode(cbFloat == sizeof(float));
Expand All @@ -1397,6 +1412,11 @@ private TextLoader(IHost host, ModelLoadContext ctx)
if (_separators.Contains(':'))
host.CheckDecode((_flags & OptionFlags.AllowSparse) == 0);

if (ctx.Header.ModelVerWritten >= 0x0001000D)
{
_decimalMarker = ctx.Reader.ReadChar();
host.CheckDecode(_decimalMarker == '.' || _decimalMarker == ',');
}
Comment thread
mstfbl marked this conversation as resolved.
_bindings = new Bindings(ctx, this);
_parser = new Parser(this);
}
Expand Down Expand Up @@ -1437,6 +1457,7 @@ void ICanSaveModel.Save(ModelSaveContext ctx)
// int: inputSize: 0 for determined from data
// int: number of separators
// char[]: separators
// char: decimal marker
// bindings
ctx.Writer.Write(sizeof(float));
ctx.Writer.Write(_maxRows);
Expand All @@ -1445,6 +1466,7 @@ void ICanSaveModel.Save(ModelSaveContext ctx)
_host.Assert(0 <= _inputSize && _inputSize < SrcLim);
ctx.Writer.Write(_inputSize);
ctx.Writer.WriteCharArray(_separators);
ctx.Writer.Write(_decimalMarker);

_bindings.Save(ctx);
}
Expand Down Expand Up @@ -1585,13 +1607,15 @@ public BoundLoader(TextLoader loader, IMultiStreamSource files)
public DataViewRowCursor GetRowCursor(IEnumerable<DataViewSchema.Column> columnsNeeded, Random rand = null)
{
_host.CheckValueOrNull(rand);
DoubleParser.DecimalMarker = _loader._decimalMarker;
var active = Utils.BuildArray(_loader._bindings.OutputSchema.Count, columnsNeeded);
return Cursor.Create(_loader, _files, active);
}

public DataViewRowCursor[] GetRowCursorSet(IEnumerable<DataViewSchema.Column> columnsNeeded, int n, Random rand = null)
{
_host.CheckValueOrNull(rand);
DoubleParser.DecimalMarker = _loader._decimalMarker;
var active = Utils.BuildArray(_loader._bindings.OutputSchema.Count, columnsNeeded);
return Cursor.CreateSet(_loader, _files, active, n);
}
Expand Down
12 changes: 12 additions & 0 deletions test/BaselineOutput/Common/EntryPoints/core_manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,18 @@
"\t"
]
},
{
"Name": "Decimal Marker",
"Type": "Char",
"Desc": "Character symbol used to separate the integer part from the fractional part of a number written in decimal form.",
"Aliases": [
"decimal"
],
"Required": false,
"SortOrder": 150.0,
"IsNullable": false,
"Default": "."
},
{
"Name": "TrimWhitespace",
"Type": "Bool",
Expand Down
35 changes: 35 additions & 0 deletions test/Microsoft.ML.Tests/TextLoaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,41 @@ public void TestTextLoaderKeyTypeBackCompat()
}
}

[Fact]
public void TestCommaAsDecimalMarker()
{
string dataPath = GetDataPath("iris_decimal_marker_as_comma.txt");

// Create a new context for ML.NET operations. It can be used for exception tracking and logging,
// as a catalog of available operations and as the source of randomness.
var mlContext = new MLContext(seed: 1);
var reader = new TextLoader(mlContext, new TextLoader.Options()
{
Columns = new[]
{
new TextLoader.Column("Label", DataKind.Single, 0),
new TextLoader.Column("Features", DataKind.Single, new [] { new TextLoader.Range(1, 4) }),
Comment thread
mstfbl marked this conversation as resolved.
Outdated
},
DecimalMarker = ','
});
// Data
var textData = reader.Load(GetDataPath(dataPath));
var data = mlContext.Data.Cache(mlContext.Transforms.Conversion.MapValueToKey("Label")
.Fit(textData).Transform(textData));

// Pipeline
var pipeline = mlContext.MulticlassClassification.Trainers.OneVersusAll(
mlContext.BinaryClassification.Trainers.LinearSvm(new Trainers.LinearSvmTrainer.Options { NumberOfIterations = 100 }),
useProbabilities: false);

var model = pipeline.Fit(data);
var predictions = model.Transform(data);

// Metrics
var metrics = mlContext.MulticlassClassification.Evaluate(predictions);
Assert.True(metrics.MicroAccuracy > 0.83);
}
Comment thread
mstfbl marked this conversation as resolved.

Comment thread
mstfbl marked this conversation as resolved.
private class IrisNoFields
{
}
Expand Down
151 changes: 151 additions & 0 deletions test/data/iris_decimal_marker_as_comma.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#Label Sepal length Sepal width Petal length Petal width
0 5,1 3,5 1,4 0,2
0 4,9 3,0 1,4 0,2
Comment thread
mstfbl marked this conversation as resolved.
0 4,7 3,2 1,3 0,2
0 4,6 3,1 1,5 0,2
0 5,0 3,6 1,4 0,2
0 5,4 3,9 1,7 0,4
0 4,6 3,4 1,4 0,3
0 5,0 3,4 1,5 0,2
0 4,4 2,9 1,4 0,2
0 4,9 3,1 1,5 0,1
0 5,4 3,7 1,5 0,2
0 4,8 3,4 1,6 0,2
0 4,8 3,0 1,4 0,1
0 4,3 3,0 1,1 0,1
0 5,8 4,0 1,2 0,2
0 5,7 4,4 1,5 0,4
0 5,4 3,9 1,3 0,4
0 5,1 3,5 1,4 0,3
0 5,7 3,8 1,7 0,3
0 5,1 3,8 1,5 0,3
0 5,4 3,4 1,7 0,2
0 5,1 3,7 1,5 0,4
0 4,6 3,6 1,0 0,2
0 5,1 3,3 1,7 0,5
0 4,8 3,4 1,9 0,2
0 5,0 3,0 1,6 0,2
0 5,0 3,4 1,6 0,4
0 5,2 3,5 1,5 0,2
0 5,2 3,4 1,4 0,2
0 4,7 3,2 1,6 0,2
0 4,8 3,1 1,6 0,2
0 5,4 3,4 1,5 0,4
0 5,2 4,1 1,5 0,1
0 5,5 4,2 1,4 0,2
0 4,9 3,1 1,5 0,1
0 5,0 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