-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseMLModel.cs
More file actions
executable file
·201 lines (153 loc) · 6.39 KB
/
BaseMLModel.cs
File metadata and controls
executable file
·201 lines (153 loc) · 6.39 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
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
using Microsoft.ML.Probabilistic.Algorithms;
using Microsoft.ML.Probabilistic.Collections;
using Microsoft.ML.Probabilistic.Distributions;
using Microsoft.ML.Probabilistic.Math;
using Microsoft.ML.Probabilistic.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UIMatrixML.Core;
namespace UIMatrixML.Modeling
{
public abstract class BaseMLModel : IMLModel
{
/* PRIVATE */
Variable<Vector> w;
InferenceEngine engine;
bool initialized = false;
bool hasHeaders = false;
/* PUBLIC */
public static object mlModelCompilation = 1;
public virtual IModelDefinition Definition { get; set; }
public virtual double Noise { get; set; }
public virtual IList<bool> Validity { get; set; }
public virtual IList<double[]> Data { get; set; }
public virtual VariableArray<bool> y { get; set; }
public virtual bool IsInitialized =>
initialized;
public virtual int FeatureCount
{
get
{
if (Data == null || Data.Count < 1)
return 0;
else
return Data[0].Length;
}
}
/// <summary>
/// Load data from CSV.
/// </summary>
/// <param name="csvFilePath">CSV file path.</param>
/// <param name="hasHeader">CSV has headers.</param>
public virtual void LoadDataFromCsv(string csvFilePath, bool hasHeader = false)
{
if (initialized == false)
throw new Exception("ML Model has not been initialized yet.");
lock (mlModelCompilation)
{
hasHeaders = hasHeader;
IEnumerable<string> csvLines = File.ReadAllLines(csvFilePath);
if (hasHeader)
csvLines = csvLines.Skip(1);
foreach (string line in csvLines)
{
IList<double> dict =
new List<double>();
string[] vals = line.Replace(" ", "").Split(",");
for (int i = 0; i < vals.Length - 1; i++)
{
dict.Add(Convert.ToDouble(vals[i]));
}
Validity.Add(Convert.ToBoolean(vals[vals.Length - 1]));
Data.Add(dict.ToArray());
}
// Create random variable w with VectorGuassian (of size 3)
// Features => (Gold | Nickel | Copper) Concentration, IsGoodMaterial?
w = Variable.Random(new VectorGaussian(Vector.Zero(FeatureCount), PositiveDefiniteMatrix.Identity(FeatureCount))).Named("w");
// Create Observable variable based on valid_ui;
y = Variable.Observed(Validity.ToArray());
BayesPointMachine.Run(this, y, w);
}
}
/// <summary>
/// Write data entry to CSV file.
/// </summary>
/// <param name="csvFilePath">CSV file path.</param>
/// <param name="features">Feature values.</param>
/// <param name="validity">Validity state.</param>
public virtual void WriteDataToCsv(string csvFilePath, IList<double> features, bool validity)
{
if (initialized == false)
throw new Exception("ML Model has not been initialized yet.");
lock (mlModelCompilation)
{
// Rebuild initial data template.
IList<string> existingLines = File.ReadAllLines(csvFilePath).ToList();
if (existingLines.Count() < 2 || existingLines.ElementAt(1).Split(",").Length - 1 != features.Count)
{
existingLines = new List<string>();
existingLines.Add(features.Select(x => $"feature_{features.IndexOf(x)}").Aggregate((c, n) => c + "," + n) + ",feature_score");
existingLines.Add(features.Select(x => $"0").Aggregate((c, n) => c + "," + n) + $",False");
File.WriteAllLines(csvFilePath, existingLines);
LoadDataFromCsv(csvFilePath, true);
}
string featuresLine = features.Select(f => Convert.ToString(f))
.Aggregate((c, n) => c + "," + n) + $",{validity}";
File.AppendAllLines(csvFilePath, new[] { featuresLine });
LoadDataFromCsv(csvFilePath, hasHeaders);
}
}
/// <summary>
/// Initialize base ML model.
/// </summary>
public virtual void Init()
{
Data =
new List<double[]>();
Validity =
new List<bool>();
lock (mlModelCompilation)
{
engine =
new InferenceEngine(new ExpectationPropagation());
initialized = true;
}
}
/// <summary>
/// Make a prediction.
/// </summary>
/// <typeparam name="TModel">Model type.</typeparam>
/// <param name="features">Feature values.</param>
/// <returns>Probability matrix is valid.</returns>
public virtual double Predict<TModel>(IList<double> features) where TModel : new()
{
if (initialized == false)
throw new Exception("ML Model has not been initialized yet.");
if (Data == null || Data.Count == 0)
throw new Exception("Dataset has 0 instances.");
if (features == null)
throw new ArgumentNullException("data");
lock (mlModelCompilation)
{
object model =
new TModel();
((BaseMLModel)model).Data =
new List<double[]>() { features.ToArray() };
VectorGaussian wPosterior =
engine.Infer<VectorGaussian>(w);
VariableArray<bool> ytest =
Variable.Array<bool>(new Range(1));
BayesPointMachine.Run(this, ytest, Variable.Random(wPosterior).Named("w"));
return (engine.Infer(ytest) as IEnumerable<Bernoulli>)
.First()
.GetProbTrue();
}
}
public abstract double Predict(IList<double> data);
public BaseMLModel()
{
}
}
}