Skip to content

Commit 20d45db

Browse files
authored
changed the directory structure for generated project (dotnet#243)
* changed the directory structure for generated project * changed test * upgraded commandline package
1 parent 584a0d6 commit 20d45db

11 files changed

+71
-40
lines changed

src/mlnet.Test/ApprovalTests/ConsoleCodeGeneratorTests.GeneratedTrainCodeTest.approved.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ namespace MyNamespace
1616
{
1717
private static string TrainDataPath = @"x:\dummypath\dummy_train.csv";
1818
private static string TestDataPath = @"x:\dummypath\dummy_test.csv";
19-
private static string ModelPath = @"..\..\..\model.zip";
19+
private static string ModelPath = @"x:\models\model.zip";
2020

2121
// Set this flag to enable the training process.
2222
private static bool EnableTraining = false;

src/mlnet.Test/ApprovalTests/ConsoleCodeGeneratorTests.cs

+6-3
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ public void GeneratedTrainCodeTest()
3535
OutputName = "MyNamespace",
3636
TrainDataset = new FileInfo("x:\\dummypath\\dummy_train.csv"),
3737
TestDataset = new FileInfo("x:\\dummypath\\dummy_test.csv"),
38-
LabelName = "Label"
38+
LabelName = "Label",
39+
ModelPath = new FileInfo("x:\\models\\model.zip")
3940
});
4041

4142
(string trainCode, string projectCode, string helperCode) = consoleCodeGen.GenerateCode();
@@ -58,7 +59,8 @@ public void GeneratedProjectCodeTest()
5859
OutputName = "MyNamespace",
5960
TrainDataset = new FileInfo("x:\\dummypath\\dummy_train.csv"),
6061
TestDataset = new FileInfo("x:\\dummypath\\dummy_test.csv"),
61-
LabelName = "Label"
62+
LabelName = "Label",
63+
ModelPath = new FileInfo("x:\\models\\model.zip")
6264
});
6365

6466
(string trainCode, string projectCode, string helperCode) = consoleCodeGen.GenerateCode();
@@ -81,7 +83,8 @@ public void GeneratedHelperCodeTest()
8183
OutputName = "MyNamespace",
8284
TrainDataset = new FileInfo("x:\\dummypath\\dummy_train.csv"),
8385
TestDataset = new FileInfo("x:\\dummypath\\dummy_test.csv"),
84-
LabelName = "Label"
86+
LabelName = "Label",
87+
ModelPath = new FileInfo("x:\\models\\model.zip")
8588
});
8689

8790
(string trainCode, string projectCode, string helperCode) = consoleCodeGen.GenerateCode();

src/mlnet/CodeGenerator/CSharp/CodeGenerator.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,8 @@ internal string GenerateTrainCode(string usings, string trainer, List<string> tr
109109
TestPath = settings.TestDataset?.FullName,
110110
TaskType = settings.MlTask.ToString(),
111111
Namespace = namespaceValue,
112-
LabelName = settings.LabelName
112+
LabelName = settings.LabelName,
113+
ModelPath = settings.ModelPath.FullName
113114
};
114115

115116
return trainingAndScoringCodeGen.TransformText();

src/mlnet/CodeGenerator/CSharp/CodeGeneratorSettings.cs

+4-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ namespace Microsoft.ML.CLI.CodeGenerator.CSharp
55
{
66
internal class CodeGeneratorSettings
77
{
8-
public string LabelName { get; internal set; }
8+
internal string LabelName { get; set; }
9+
10+
internal FileInfo ModelPath { get; set; }
11+
912
internal string OutputName { get; set; }
1013

1114
internal string OutputBaseDir { get; set; }

src/mlnet/Commands/CommandDefinitions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ Option Verbosity() =>
8989

9090
Option Name() =>
9191
new Option(new List<string>() { "--name" }, "Name for the output project or solution to create. ",
92-
new Argument<string>(defaultValue: "Sample"));
92+
new Argument<string>());
9393

9494
Option OutputPath() =>
9595
new Option(new List<string>() { "--output-path" }, "Location folder to place the generated output. The default is the current directory.",

src/mlnet/Commands/New/NewCommandHandler.cs

+7-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6+
using System.IO;
67
using Microsoft.Data.DataView;
78
using Microsoft.ML.Auto;
89
using Microsoft.ML.CLI.CodeGenerator.CSharp;
@@ -75,10 +76,11 @@ public void Execute()
7576

7677
// Save the model
7778
logger.Log(LogLevel.Info, Strings.SavingBestModel);
78-
Utils.SaveModel(model, settings.OutputPath.FullName, $"model.zip", context);
79+
var modelPath = new FileInfo(Path.Combine(settings.OutputPath.FullName, $"model.zip"));
80+
Utils.SaveModel(model, modelPath, context);
7981

8082
// Generate the Project
81-
GenerateProject(columnInference, pipeline, sanitized_Label_Name);
83+
GenerateProject(columnInference, pipeline, sanitized_Label_Name, modelPath);
8284
}
8385

8486
internal ColumnInferenceResults InferColumns(MLContext context)
@@ -99,7 +101,7 @@ internal ColumnInferenceResults InferColumns(MLContext context)
99101
return columnInference;
100102
}
101103

102-
internal void GenerateProject(ColumnInferenceResults columnInference, Pipeline pipeline, string labelName)
104+
internal void GenerateProject(ColumnInferenceResults columnInference, Pipeline pipeline, string labelName, FileInfo modelPath)
103105
{
104106
//Generate code
105107
logger.Log(LogLevel.Info, $"{Strings.GenerateProject} : {settings.OutputPath.FullName}");
@@ -113,7 +115,8 @@ internal void GenerateProject(ColumnInferenceResults columnInference, Pipeline p
113115
TestDataset = settings.TestDataset,
114116
OutputName = settings.Name,
115117
OutputBaseDir = settings.OutputPath.FullName,
116-
LabelName = labelName
118+
LabelName = labelName,
119+
ModelPath = modelPath
117120
});
118121
codeGenerator.GenerateOutput();
119122
}

src/mlnet/Program.cs

+18-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.CommandLine.Builder;
77
using System.CommandLine.Invocation;
8+
using System.IO;
89
using Microsoft.ML.CLI.Commands;
910
using Microsoft.ML.CLI.Commands.New;
1011
using Microsoft.ML.CLI.Data;
@@ -25,13 +26,29 @@ public static void Main(string[] args)
2526
// Map the verbosity to internal levels
2627
var verbosity = Utils.GetVerbosity(options.Verbosity);
2728

29+
// Build the output path
30+
string outputBaseDir = string.Empty;
31+
if (options.Name == null)
32+
{
33+
var datasetName = Path.GetFileNameWithoutExtension(options.Dataset.FullName);
34+
options.Name = Utils.Sanitize(datasetName) + "_" + Utils.GetTaskKind(options.MlTask).ToString();
35+
outputBaseDir = Path.Combine(options.OutputPath.FullName, options.Name);
36+
}
37+
else
38+
{
39+
outputBaseDir = Path.Combine(options.OutputPath.FullName, options.Name);
40+
}
41+
42+
// Override the output path
43+
options.OutputPath = new DirectoryInfo(outputBaseDir);
44+
2845
// Instantiate the command
2946
var command = new NewCommand(options);
3047

3148
// Override the Logger Configuration
3249
var logconsole = LogManager.Configuration.FindTargetByName("logconsole");
3350
var logfile = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
34-
logfile.FileName = $"{options.OutputPath.FullName}/debug_log.txt";
51+
logfile.FileName = $"{outputBaseDir}/logs/debug_log.txt";
3552
var config = LogManager.Configuration;
3653
config.AddRule(verbosity, LogLevel.Fatal, logconsole);
3754

src/mlnet/Templates/Console/MLCodeGen.cs

+23-21
Original file line numberDiff line numberDiff line change
@@ -41,27 +41,28 @@ public virtual string TransformText()
4141
this.Write(this.ToStringHelper.ToStringWithCulture(TestPath));
4242
this.Write("\";\r\n");
4343
}
44-
this.Write(" private static string ModelPath = @\"..\\..\\..\\model.zip\";\r\n\r\n // Se" +
45-
"t this flag to enable the training process.\r\n private static bool EnableT" +
46-
"raining = false;\r\n\r\n static void Main(string[] args)\r\n {\r\n " +
47-
" // Create MLContext to be shared across the model creation workflow objects " +
48-
"\r\n // Set a random seed for repeatable/deterministic results across m" +
49-
"ultiple trainings.\r\n var mlContext = new MLContext(seed: 1);\r\n\r\n " +
50-
" if (EnableTraining)\r\n {\r\n // Create, Train, Eva" +
51-
"luate and Save a model\r\n BuildTrainEvaluateAndSaveModel(mlContext" +
52-
");\r\n ConsoleHelper.ConsoleWriteHeader(\"=============== End of tra" +
53-
"ining process ===============\");\r\n }\r\n else\r\n {" +
54-
"\r\n ConsoleHelper.ConsoleWriteHeader(\"Skipping the training proces" +
55-
"s. Please set the flag : \'EnableTraining\' to \'true\' to enable the training proce" +
56-
"ss.\");\r\n }\r\n\r\n // Make a single test prediction loading th" +
57-
"e model from .ZIP file\r\n TestSinglePrediction(mlContext);\r\n\r\n " +
58-
" ConsoleHelper.ConsoleWriteHeader(\"=============== End of process, hit any ke" +
59-
"y to finish ===============\");\r\n Console.ReadKey();\r\n\r\n }\r\n\r\n " +
60-
" private static ITransformer BuildTrainEvaluateAndSaveModel(MLContext mlCo" +
61-
"ntext)\r\n {\r\n // Data loading\r\n IDataView trainingDa" +
62-
"taView = mlContext.Data.ReadFromTextFile<SampleObservation>(\r\n " +
63-
" path: TrainDataPath,\r\n " +
64-
" hasHeader : ");
44+
this.Write(" private static string ModelPath = @\"");
45+
this.Write(this.ToStringHelper.ToStringWithCulture(ModelPath));
46+
this.Write("\";\r\n\r\n // Set this flag to enable the training process.\r\n private s" +
47+
"tatic bool EnableTraining = false;\r\n\r\n static void Main(string[] args)\r\n " +
48+
" {\r\n // Create MLContext to be shared across the model creation" +
49+
" workflow objects \r\n // Set a random seed for repeatable/deterministi" +
50+
"c results across multiple trainings.\r\n var mlContext = new MLContext(" +
51+
"seed: 1);\r\n\r\n if (EnableTraining)\r\n {\r\n // " +
52+
"Create, Train, Evaluate and Save a model\r\n BuildTrainEvaluateAndS" +
53+
"aveModel(mlContext);\r\n ConsoleHelper.ConsoleWriteHeader(\"========" +
54+
"======= End of training process ===============\");\r\n }\r\n e" +
55+
"lse\r\n {\r\n ConsoleHelper.ConsoleWriteHeader(\"Skipping t" +
56+
"he training process. Please set the flag : \'EnableTraining\' to \'true\' to enable " +
57+
"the training process.\");\r\n }\r\n\r\n // Make a single test pre" +
58+
"diction loading the model from .ZIP file\r\n TestSinglePrediction(mlCon" +
59+
"text);\r\n\r\n ConsoleHelper.ConsoleWriteHeader(\"=============== End of p" +
60+
"rocess, hit any key to finish ===============\");\r\n Console.ReadKey();" +
61+
"\r\n\r\n }\r\n\r\n private static ITransformer BuildTrainEvaluateAndSaveMo" +
62+
"del(MLContext mlContext)\r\n {\r\n // Data loading\r\n ID" +
63+
"ataView trainingDataView = mlContext.Data.ReadFromTextFile<SampleObservation>(\r\n" +
64+
" path: TrainDataPath,\r\n " +
65+
" hasHeader : ");
6566
this.Write(this.ToStringHelper.ToStringWithCulture(HasHeader.ToString().ToLowerInvariant()));
6667
this.Write(",\r\n separatorChar : \'");
6768
this.Write(this.ToStringHelper.ToStringWithCulture(Regex.Escape(Separator.ToString())));
@@ -260,6 +261,7 @@ private static void TestSinglePrediction(MLContext mlContext)
260261
public int Kfolds {get;set;} = 5;
261262
public string Namespace {get;set;}
262263
public string LabelName {get;set;}
264+
public string ModelPath {get;set;}
263265

264266
}
265267
#region Base class

src/mlnet/Templates/Console/MLCodeGen.tt

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ namespace <#= Namespace #>
2424
<#if(!string.IsNullOrEmpty(TestPath)){ #>
2525
private static string TestDataPath = @"<#= TestPath #>";
2626
<# } #>
27-
private static string ModelPath = @"..\..\..\model.zip";
27+
private static string ModelPath = @"<#= ModelPath #>";
2828

2929
// Set this flag to enable the training process.
3030
private static bool EnableTraining = false;
@@ -215,4 +215,5 @@ public bool TrimWhiteSpace {get;set;}
215215
public int Kfolds {get;set;} = 5;
216216
public string Namespace {get;set;}
217217
public string LabelName {get;set;}
218+
public string ModelPath {get;set;}
218219
#>

src/mlnet/Utilities/Utils.cs

+6-5
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,15 @@ internal static LogLevel GetVerbosity(string verbosity)
2929
}
3030

3131

32-
internal static void SaveModel(ITransformer model, string ModelPath, string modelName, MLContext mlContext)
32+
internal static void SaveModel(ITransformer model, FileInfo modelPath, MLContext mlContext)
3333
{
34-
if (!Directory.Exists(ModelPath))
34+
35+
if (!Directory.Exists(modelPath.Directory.FullName))
3536
{
36-
Directory.CreateDirectory(ModelPath);
37+
Directory.CreateDirectory(modelPath.Directory.FullName);
3738
}
38-
ModelPath = Path.Combine(ModelPath, modelName);
39-
using (var fs = File.Create(ModelPath))
39+
40+
using (var fs = File.Create(modelPath.FullName))
4041
model.SaveTo(mlContext, fs);
4142
}
4243

src/mlnet/mlnet.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
<ItemGroup>
1414
<PackageReference Include="Microsoft.CodeAnalysis" Version="2.10.0" />
1515
<PackageReference Include="NLog" Version="4.5.11" />
16-
<PackageReference Include="System.CommandLine.Experimental" Version="0.1.0-alpha-63825-02" />
16+
<PackageReference Include="System.CommandLine.Experimental" Version="0.1.0-alpha-63828-02" />
1717
</ItemGroup>
1818

1919
<ItemGroup>

0 commit comments

Comments
 (0)