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
use crate::*;
use arcis_interpreter_proc_macros::encrypted_library;
#[encrypted_library]
mod arcis_library {
const MAX_FEATURES: usize = 100;
/// Inverse of the standard logistic function.
pub fn logit(p: f64) -> f64 {
if p <= 0.0 || p >= 1.0 {
0.0
} else {
p.ln() - (1.0 - p).ln()
}
}
/// Standard logistic function.
pub fn expit(x: f64) -> f64 {
ArcisMath::sigmoid(x)
}
pub struct LogisticRegression {
pub coef: [f64; MAX_FEATURES],
pub intercept: f64,
pub n_features: usize,
}
impl LogisticRegression {
#[allow(clippy::manual_memcpy)]
pub fn new(coef: &[f64], intercept: f64) -> Self {
let mut arr = [0.0; MAX_FEATURES];
let n = coef.len();
// assert!(n <= MAX_FEATURES, "Too many features");
// Not supported: silently truncate if too many features
let n = if n > MAX_FEATURES { MAX_FEATURES } else { n };
for i in 0..n {
arr[i] = coef[i];
}
LogisticRegression {
coef: arr,
intercept,
n_features: n,
}
}
pub fn predict_log_proba(&self, x: &[f64]) -> f64 {
if x.len() != self.n_features {
// panic!("`coef` and `x` must be of same length (found {} and {})",
// self.n_features, x.len()); Not supported: return default value
0.0
} else {
let mut acc = self.intercept;
for (i, xi) in x.iter().enumerate().take(self.n_features) {
acc += self.coef[i] * xi;
}
acc
}
}
pub fn predict_proba(&self, x: &[f64]) -> f64 {
expit(Self::predict_log_proba(self, x))
}
pub fn predict(&self, x: &[f64], threshold: f64) -> bool {
Self::predict_log_proba(self, x) > logit(threshold)
}
}
pub struct LinearRegression {
pub coef: [f64; MAX_FEATURES],
pub intercept: f64,
pub n_features: usize,
}
impl LinearRegression {
#[allow(clippy::manual_memcpy)]
pub fn new(coef: &[f64], intercept: f64) -> Self {
let mut arr = [0.0; MAX_FEATURES];
let n = coef.len();
// assert!(n <= MAX_FEATURES, "Too many features");
// Not supported: silently truncate if too many features
let n = if n > MAX_FEATURES { MAX_FEATURES } else { n };
for i in 0..n {
arr[i] = coef[i];
}
LinearRegression {
coef: arr,
intercept,
n_features: n,
}
}
pub fn predict(&self, x: &[f64]) -> f64 {
if x.len() != self.n_features {
// panic!("`coef` and `x` must be of same length (found {} and {})",
// self.n_features, x.len()); Not supported: return default value
0.0
} else {
let mut acc = self.intercept;
for (i, xi) in x.iter().enumerate().take(self.n_features) {
acc += self.coef[i] * xi;
}
acc
}
}
}
}