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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use rhai::plugin::*;
/// Documentation for the module
#[export_module]
pub mod train_and_predict_functions {
use rhai::{Array, Dynamic, EvalAltResult, ImmutableString, Position, FLOAT, INT};
use smartcorelib::{
linalg::basic::matrix::DenseMatrix,
linear::{
lasso::{Lasso, LassoParameters},
linear_regression::{LinearRegression, LinearRegressionParameters},
logistic_regression::{LogisticRegression, LogisticRegressionParameters},
},
};
fn array_to_vec_float(arr: &mut Array) -> Vec<FLOAT> {
arr.into_iter()
.map(|el| el.as_float().unwrap())
.collect::<Vec<FLOAT>>()
}
#[derive(Clone)]
pub struct Model {
saved_model: Vec<u8>,
model_type: String,
}
impl Default for Model {
fn default() -> Self {
Model {
saved_model: vec![],
model_type: String::new(),
}
}
}
/// Trains a [`smartcore`](https://smartcorelib.org/) machine learning model. The model can then
/// be used to make predictions with the [`predict`](#predictx-array-model-model---array)
/// function Available model types are:
/// 1. `linear` - ordinary least squares linear regression
/// 2. `logistic` - logistic regression
/// 3. `lasso` - lasso regression
/// ```typescript
/// let xdata = [[1.0, 2.0],
/// [2.0, 3.0],
/// [3.0, 4.0]];
/// let ydata = [1.0, 2.0, 3.0];
/// let model = train(xdata, ydata, "linear");
/// true;
/// ```
#[rhai_fn(name = "train", return_raw, pure)]
pub fn train_model(
x: &mut Array,
y: Array,
algorithm: ImmutableString,
) -> Result<Model, Box<EvalAltResult>> {
// Make x array
let array_as_vec_vec_float = &x
.into_iter()
.map(|observation| {
crate::train_and_predict_functions::array_to_vec_float(
&mut observation.clone().into_array().unwrap(),
)
})
.collect::<Vec<Vec<FLOAT>>>();
// Check if x array is empty
if array_as_vec_vec_float.len() == 0 {
Err(EvalAltResult::ErrorArrayBounds(0, 0, Position::NONE).into())
} else {
let algorithm_string = algorithm.as_str();
let xvec = smartcorelib::linalg::basic::matrix::DenseMatrix::from_2d_vec(
array_as_vec_vec_float,
);
match algorithm_string {
"linear" => {
let yvec = y
.clone()
.into_iter()
.map(|el| el.as_float().unwrap())
.collect::<Vec<FLOAT>>();
match LinearRegression::fit(&xvec, &yvec, LinearRegressionParameters::default())
{
Ok(model) => Ok(Model {
saved_model: bincode::serialize(&model).unwrap(),
model_type: algorithm_string.to_string(),
}),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
}
}
"lasso" => {
let yvec = y
.clone()
.into_iter()
.map(|el| el.as_float().unwrap())
.collect::<Vec<FLOAT>>();
match Lasso::fit(&xvec, &yvec, LassoParameters::default()) {
Ok(model) => Ok(Model {
saved_model: bincode::serialize(&model).unwrap(),
model_type: algorithm_string.to_string(),
}),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
}
}
"logistic" => {
let yvec = y
.clone()
.into_iter()
.map(|el| el.as_int().unwrap())
.collect::<Vec<INT>>();
match LogisticRegression::fit(
&xvec,
&yvec,
LogisticRegressionParameters::default(),
) {
Ok(model) => Ok(Model {
saved_model: bincode::serialize(&model).unwrap(),
model_type: algorithm_string.to_string(),
}),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
}
}
&_ => Err(EvalAltResult::ErrorArithmetic(
format!("{} is not a recognized model type.", algorithm_string),
Position::NONE,
)
.into()),
}
}
}
/// Uses a [`smartcore`](https://smartcorelib.org/) machine learning model (trained with the
/// [`train`](#trainx-array-y-array-algorithm-immutablestring---model) function to predict
/// dependent variables.
/// ```typescript
/// let xdata = [[1.0, 2.0],
/// [2.0, 3.0],
/// [3.0, 4.0]];
/// let ydata = [1.0, 2.0, 3.0];
/// let model = train(xdata, ydata, "linear");
/// let ypred = predict(xdata, model);
/// true
/// ```
#[rhai_fn(name = "predict", return_raw, pure)]
pub fn predict_with_model(x: &mut Array, model: Model) -> Result<Array, Box<EvalAltResult>> {
// Make x array
let array_as_vec_vec_float = &x
.into_iter()
.map(|observation| {
crate::train_and_predict_functions::array_to_vec_float(
&mut observation.clone().into_array().unwrap(),
)
})
.collect::<Vec<Vec<FLOAT>>>();
// Check if x array is empty
if array_as_vec_vec_float.len() == 0 {
Err(EvalAltResult::ErrorArrayBounds(0, 0, Position::NONE).into())
} else {
let xvec = DenseMatrix::from_2d_vec(array_as_vec_vec_float);
let algorithm_string = model.model_type.as_str();
match algorithm_string {
"linear" => {
let model_ready: LinearRegression<
FLOAT,
FLOAT,
DenseMatrix<FLOAT>,
Vec<FLOAT>,
> = bincode::deserialize(&*model.saved_model).unwrap();
return match model_ready.predict(&xvec) {
Ok(y) => Ok(y
.into_iter()
.map(|observation| Dynamic::from_float(observation))
.collect::<Vec<Dynamic>>()),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
};
}
"lasso" => {
let model_ready: Lasso<FLOAT, FLOAT, DenseMatrix<FLOAT>, Vec<FLOAT>> =
bincode::deserialize(&*model.saved_model).unwrap();
return match model_ready.predict(&xvec) {
Ok(y) => Ok(y
.into_iter()
.map(|observation| Dynamic::from_float(observation))
.collect::<Vec<Dynamic>>()),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
};
}
"logistic" => {
let model_ready: LogisticRegression<FLOAT, INT, DenseMatrix<FLOAT>, Vec<INT>> =
bincode::deserialize(&*model.saved_model).unwrap();
return match model_ready.predict(&xvec) {
Ok(y) => Ok(y
.into_iter()
.map(|observation| Dynamic::from_int(observation))
.collect::<Vec<Dynamic>>()),
Err(e) => Err(EvalAltResult::ErrorArithmetic(
format!("{e}"),
Position::NONE,
)
.into()),
};
}
&_ => Err(EvalAltResult::ErrorArithmetic(
format!("{} is not a recognized model type.", algorithm_string),
Position::NONE,
)
.into()),
}
}
}
}