|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Text; |
| 5 | +using Microsoft.ML; |
| 6 | +using Microsoft.ML.Data; |
| 7 | + |
| 8 | +namespace Samples.Dynamic.DataOperations |
| 9 | +{ |
| 10 | + public static class LoadingText |
| 11 | + { |
| 12 | + // This examples shows all the ways to load data with TextLoader. |
| 13 | + public static void Example() |
| 14 | + { |
| 15 | + // Create 5 data files to illustrate different loading methods. |
| 16 | + var dataFiles = new List<string>(); |
| 17 | + var random = new Random(); |
| 18 | + var dataDirectoryName = "DataDir"; |
| 19 | + Directory.CreateDirectory(dataDirectoryName); |
| 20 | + for (int i = 0; i < 5; i++) |
| 21 | + { |
| 22 | + var fileName = Path.Combine(dataDirectoryName, $"Data_{i}.csv"); |
| 23 | + dataFiles.Add(fileName); |
| 24 | + using (var fs = File.CreateText(fileName)) |
| 25 | + // Write random lines without header |
| 26 | + for (int line = 0; line < 10; line++) |
| 27 | + fs.WriteLine(random.NextDouble().ToString()); |
| 28 | + } |
| 29 | + |
| 30 | + // Create a TextLoader. |
| 31 | + var mlContext = new MLContext(); |
| 32 | + var loader = mlContext.Data.CreateTextLoader( |
| 33 | + columns: new[] |
| 34 | + { |
| 35 | + new TextLoader.Column("RandomFeature", DataKind.Single, 0) |
| 36 | + }, |
| 37 | + hasHeader: false |
| 38 | + ); |
| 39 | + |
| 40 | + // Load a single file from path. |
| 41 | + var singleFileData = loader.Load(dataFiles[0]); |
| 42 | + PrintRowCount(singleFileData); |
| 43 | + |
| 44 | + // Expected Output: |
| 45 | + // 10 |
| 46 | + |
| 47 | + |
| 48 | + // Load all 5 files from path. |
| 49 | + var multipleFilesData = loader.Load(dataFiles.ToArray()); |
| 50 | + PrintRowCount(multipleFilesData); |
| 51 | + |
| 52 | + // Expected Output: |
| 53 | + // 50 |
| 54 | + |
| 55 | + |
| 56 | + // Load all files using path wildcard. |
| 57 | + var multipleFilesWildcardData = |
| 58 | + loader.Load(Path.Combine(dataDirectoryName, "*")); |
| 59 | + PrintRowCount(multipleFilesWildcardData); |
| 60 | + |
| 61 | + // Expected Output: |
| 62 | + // 50 |
| 63 | + } |
| 64 | + |
| 65 | + private static void PrintRowCount(IDataView idv) |
| 66 | + { |
| 67 | + // IDataView is lazy so we need to iterate through it |
| 68 | + // to get the number of rows. |
| 69 | + long rowCount = 0; |
| 70 | + using (var cursor = idv.GetRowCursor(idv.Schema)) |
| 71 | + while (cursor.MoveNext()) |
| 72 | + rowCount++; |
| 73 | + |
| 74 | + Console.WriteLine(rowCount); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments