-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
171 lines (152 loc) · 6.26 KB
/
Program.cs
File metadata and controls
171 lines (152 loc) · 6.26 KB
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
using MinimalTextClassifier.Core;
using Serilog;
using Serilog.Events;
using System.Diagnostics;
public static class Program
{
public static void AddConsoleLogger()
{
var serilogLogger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.Console(
restrictedToMinimumLevel: LogEventLevel.Debug,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
path: "classifier_test.log",
restrictedToMinimumLevel: LogEventLevel.Debug,
rollingInterval: RollingInterval.Infinite,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: 100 * 1024 * 1024, // 100 MB
retainedFileCountLimit: 5)
.CreateLogger();
Log.Logger = serilogLogger;
Log.Information("Serilog configured.");
}
public static async Task Main(string[] args)
{
AddConsoleLogger();
Log.Information("Train model? Y/n");
var answer = Console.ReadKey(false);
if (char.ToLower(answer.KeyChar) == 'y')
{
// Step 1: Run the Python training script with real-time output streaming
// (text classification fine-tuning, specifically binary classification)
bool didComplete = await TuneModelPythonScript();
if (!didComplete)
{
return;
}
}
// Step 2: Load the fine-tuned model (generated by Python)
string trainedModelPath = "deberta_v3_small_fine_tuned_int8.onnx";
if (!File.Exists(trainedModelPath))
{
Log.Error("Trained model not found at {Path}", trainedModelPath);
return;
}
var classifier = new MinimalTransformerClassifier(trainedModelPath);
// Step 3 & 4: Test the classifier with the trained model
// Step 3 & 4: Run batch tests on positive and negative examples
const float cutoff = 0.5f;
TestModel(classifier, cutoff);
}
private static void TestModel(MinimalTransformerClassifier classifier, float confidenceMax)
{
// Load positive examples
string positivePath = "positive_examples.txt";
if (!File.Exists(positivePath))
{
Log.Error("Positive examples file not found at {Path}", positivePath);
return;
}
var positiveExamples = File.ReadAllLines(positivePath)
.Select(line => line.Trim().Trim('"', '\''))
.Where(line => !string.IsNullOrWhiteSpace(line))
.ToList();
// Load negative examples
string negativePath = "negative_examples.txt";
if (!File.Exists(negativePath))
{
Log.Error("Negative examples file not found at {Path}", negativePath);
return;
}
var negativeExamples = File.ReadAllLines(negativePath)
.Select(line => line.Trim().Trim('"', '\''))
.Where(line => !string.IsNullOrWhiteSpace(line))
.ToList();
// Test positives (expect true)
int positiveCorrect = 0;
foreach (var example in positiveExamples)
{
var conf = classifier.ClassifyText(example);
bool isWake = conf > confidenceMax;
if (isWake)
positiveCorrect++;
Log.Debug("Positive example: '{Text}' -> IsWake: {IsWake}, Conf: {Conf:F3}", example, isWake, conf);
}
// Test negatives (expect false)
int negativeCorrect = 0;
foreach (var example in negativeExamples)
{
var conf = classifier.ClassifyText(example);
bool isWake = conf > confidenceMax;
if (!isWake)
negativeCorrect++;
Log.Debug("Negative example: '{Text}' -> IsWake: {IsWake}, Conf: {Conf:F3}", example, isWake, conf);
}
// Calculate and log percentages
double positiveAccuracy = (double)positiveCorrect / positiveExamples.Count * 100;
double negativeAccuracy = (double)negativeCorrect / negativeExamples.Count * 100;
Log.Information("Test Results:");
Log.Information("Positive examples accuracy: {Accuracy:F2}% ({Correct}/{Total})", positiveAccuracy, positiveCorrect, positiveExamples.Count);
Log.Information("Negative examples accuracy: {Accuracy:F2}% ({Correct}/{Total})", negativeAccuracy, negativeCorrect, negativeExamples.Count);
}
private static async Task<bool> TuneModelPythonScript()
{
Log.Information("Starting Python training script...");
var pythonProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "python",
Arguments = "train_model.py", // Assumes script is in current dir
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
},
EnableRaisingEvents = true // For OutputDataReceived
};
// Set up real-time output streaming
pythonProcess.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
//Console.WriteLine(e.Data); // Print to terminal
Log.Information("->{data}", e.Data);
}
};
pythonProcess.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
//Console.Error.WriteLine(e.Data); // Print errors to stderr/terminal
Log.Information("->{data}", e.Data);
}
};
pythonProcess.Start();
pythonProcess.BeginOutputReadLine();
pythonProcess.BeginErrorReadLine();
await Task.Run(() => pythonProcess.WaitForExit()); // Wait async
if (pythonProcess.ExitCode != 0)
{
Log.Error("Python training failed with exit code {Code}", pythonProcess.ExitCode);
return false;
}
Log.Information("Python training completed successfully.");
return true;
}
}