sklears-feature-extraction 0.2.0

Feature extraction from raw data (text, images)
Documentation
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::neural_types::*;
use super::neural_activations::*;
use super::neural_utilities::*;
use scirs2_core::ndarray::s;

pub struct AttentionFeatureExtractor {
    pub attention_type: AttentionType,
    pub d_model: usize,
    pub n_heads: usize,
    pub seq_length: usize,
    pub learning_rate: f64,
    pub n_epochs: usize,
    pub batch_size: usize,
    pub regularization: f64,
    pub random_state: Option<u64>,
    pub dropout_rate: f64,
    pub use_layer_norm: bool,
    pub temperature: f64,
}

impl AttentionFeatureExtractor {
    pub fn new() -> Self {
        Self {
            attention_type: AttentionType::Scaled,
            d_model: 512,
            n_heads: 8,
            seq_length: 128,
            learning_rate: 0.0001,
            n_epochs: 50,
            batch_size: 32,
            regularization: 0.01,
            random_state: None,
            dropout_rate: 0.1,
            use_layer_norm: true,
            temperature: 1.0,
        }
    }

    pub fn attention_type(mut self, attention_type: AttentionType) -> Self {
        self.attention_type = attention_type;
        self
    }

    pub fn d_model(mut self, d_model: usize) -> Self {
        self.d_model = d_model;
        self
    }

    pub fn n_heads(mut self, n_heads: usize) -> Self {
        self.n_heads = n_heads;
        self
    }

    pub fn seq_length(mut self, length: usize) -> Self {
        self.seq_length = length;
        self
    }

    pub fn learning_rate(mut self, lr: f64) -> Self {
        self.learning_rate = lr;
        self
    }

    pub fn n_epochs(mut self, epochs: usize) -> Self {
        self.n_epochs = epochs;
        self
    }

    pub fn batch_size(mut self, size: usize) -> Self {
        self.batch_size = size;
        self
    }

    pub fn regularization(mut self, reg: f64) -> Self {
        self.regularization = reg;
        self
    }

    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    pub fn dropout_rate(mut self, rate: f64) -> Self {
        self.dropout_rate = rate;
        self
    }

    pub fn use_layer_norm(mut self, use_norm: bool) -> Self {
        self.use_layer_norm = use_norm;
        self
    }

    pub fn temperature(mut self, temp: f64) -> Self {
        self.temperature = temp;
        self
    }

    fn initialize_weights(&self, input_dim: usize, output_dim: usize) -> Array2<f64> {
        let mut rng = match self.random_state {
            Some(seed) => Random::seed_from_u64(seed),
            None => Random::seed_from_u64(42),
        };

        let scale = (2.0 / (input_dim + output_dim) as f64).sqrt();
        let mut weights = Array2::zeros((input_dim, output_dim));

        for i in 0..input_dim {
            for j in 0..output_dim {
                weights[(i, j)] = rng.gen_range(-scale..scale);
            }
        }

        weights
    }

    fn scaled_dot_product_attention(
        &self,
        q: &Array2<f64>,
        k: &Array2<f64>,
        v: &Array2<f64>,
    ) -> Array2<f64> {
        let d_k = k.ncols() as f64;
        let scores = q.dot(&k.t()) / (d_k.sqrt() * self.temperature);

        let attention_weights = self.apply_softmax_2d(&scores);
        attention_weights.dot(v)
    }

    fn additive_attention(
        &self,
        q: &Array2<f64>,
        k: &Array2<f64>,
        v: &Array2<f64>,
        w_a: &Array2<f64>,
        w_b: &Array2<f64>,
        w_v: &Array1<f64>,
    ) -> Array2<f64> {
        let q_proj = q.dot(w_a);
        let k_proj = k.dot(w_b);

        let mut energy = Array2::zeros((q.nrows(), k.nrows()));

        for i in 0..q.nrows() {
            for j in 0..k.nrows() {
                let mut sum = 0.0;
                for l in 0..w_v.len() {
                    sum += w_v[l] * (q_proj[(i, l)] + k_proj[(j, l)]).tanh();
                }
                energy[(i, j)] = sum;
            }
        }

        let attention_weights = self.apply_softmax_2d(&energy);
        attention_weights.dot(v)
    }

    fn multiplicative_attention(
        &self,
        q: &Array2<f64>,
        k: &Array2<f64>,
        v: &Array2<f64>,
        w: &Array2<f64>,
    ) -> Array2<f64> {
        let q_transformed = q.dot(w);
        let scores = q_transformed.dot(&k.t());

        let attention_weights = self.apply_softmax_2d(&scores);
        attention_weights.dot(v)
    }

    fn multi_head_attention(
        &self,
        q: &Array2<f64>,
        k: &Array2<f64>,
        v: &Array2<f64>,
        w_q: &Array2<f64>,
        w_k: &Array2<f64>,
        w_v: &Array2<f64>,
        w_o: &Array2<f64>,
    ) -> Array2<f64> {
        let d_k = self.d_model / self.n_heads;
        let mut head_outputs = Vec::new();

        for head in 0..self.n_heads {
            let start_idx = head * d_k;
            let end_idx = start_idx + d_k;

            let q_head = q.dot(&w_q.slice(s![.., start_idx..end_idx]));
            let k_head = k.dot(&w_k.slice(s![.., start_idx..end_idx]));
            let v_head = v.dot(&w_v.slice(s![.., start_idx..end_idx]));

            let head_output = self.scaled_dot_product_attention(&q_head, &k_head, &v_head);
            head_outputs.push(head_output);
        }

        let concatenated = self.concatenate_heads(&head_outputs);
        concatenated.dot(w_o)
    }

    fn concatenate_heads(&self, heads: &[Array2<f64>]) -> Array2<f64> {
        let seq_len = heads[0].nrows();
        let total_dim = heads.iter().map(|h| h.ncols()).sum();
        let mut result = Array2::zeros((seq_len, total_dim));

        let mut col_offset = 0;
        for head in heads {
            let head_dim = head.ncols();
            for i in 0..seq_len {
                for j in 0..head_dim {
                    result[(i, col_offset + j)] = head[(i, j)];
                }
            }
            col_offset += head_dim;
        }

        result
    }

    fn apply_softmax_2d(&self, x: &Array2<f64>) -> Array2<f64> {
        let mut result = Array2::zeros(x.raw_dim());

        for i in 0..x.nrows() {
            let row = x.row(i);
            let max_val = row.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));

            let exp_row: Vec<f64> = row.iter().map(|&val| (val - max_val).exp()).collect();
            let sum_exp: f64 = exp_row.iter().sum();

            for (j, &exp_val) in exp_row.iter().enumerate() {
                result[(i, j)] = exp_val / sum_exp;
            }
        }

        result
    }

    fn apply_dropout(&self, x: &Array2<f64>) -> Array2<f64> {
        let mut rng = Random::seed_from_u64(42);
        let mut result = x.clone();

        for elem in result.iter_mut() {
            if rng.random_range(0.0..1.0) < self.dropout_rate {
                *elem = 0.0;
            } else {
                *elem /= 1.0 - self.dropout_rate;
            }
        }

        result
    }

    fn layer_normalize(&self, x: &Array2<f64>) -> Array2<f64> {
        if !self.use_layer_norm {
            return x.clone();
        }

        layer_norm(x)
    }

    fn positional_encoding(&self, seq_len: usize, d_model: usize) -> Array2<f64> {
        let mut pe = Array2::zeros((seq_len, d_model));

        for pos in 0..seq_len {
            for i in 0..d_model {
                let angle = pos as f64 / (10000.0_f64).powf((2 * (i / 2)) as f64 / d_model as f64);
                if i % 2 == 0 {
                    pe[(pos, i)] = angle.sin();
                } else {
                    pe[(pos, i)] = angle.cos();
                }
            }
        }

        pe
    }
}

pub struct FittedAttentionFeatureExtractor {
    extractor: AttentionFeatureExtractor,
    w_q: Array2<f64>,
    w_k: Array2<f64>,
    w_v: Array2<f64>,
    w_o: Array2<f64>,
    w_a: Option<Array2<f64>>,
    w_b: Option<Array2<f64>>,
    w_v_add: Option<Array1<f64>>,
    w_mult: Option<Array2<f64>>,
    positional_encoding: Array2<f64>,
    input_shape: (usize, usize),
}

impl Estimator<Untrained> for AttentionFeatureExtractor {
    fn estimator_type(&self) -> &'static str {
        "AttentionFeatureExtractor"
    }

    fn complexity(&self) -> f64 {
        (self.d_model * self.seq_length) as f64
    }
}

impl Fit<Array2<f64>, ()> for AttentionFeatureExtractor {
    type Output = FittedAttentionFeatureExtractor;

    fn fit(&self, x: &Array2<f64>, _y: &()) -> SklResult<Self::Output> {
        let (seq_len, d_input) = x.dim();

        if seq_len == 0 || d_input == 0 {
            return Err(SklearsError::InvalidInput("Empty input data".to_string()));
        }

        if self.d_model % self.n_heads != 0 {
            return Err(SklearsError::InvalidInput(
                "d_model must be divisible by n_heads".to_string()
            ));
        }

        let w_q = self.initialize_weights(d_input, self.d_model);
        let w_k = self.initialize_weights(d_input, self.d_model);
        let w_v = self.initialize_weights(d_input, self.d_model);
        let w_o = self.initialize_weights(self.d_model, self.d_model);

        let (w_a, w_b, w_v_add) = match self.attention_type {
            AttentionType::Additive => {
                let w_a = Some(self.initialize_weights(self.d_model, self.d_model));
                let w_b = Some(self.initialize_weights(self.d_model, self.d_model));
                let w_v_add = Some(Array1::zeros(self.d_model));
                (w_a, w_b, w_v_add)
            },
            _ => (None, None, None),
        };

        let w_mult = match self.attention_type {
            AttentionType::Multiplicative => {
                Some(self.initialize_weights(self.d_model, self.d_model))
            },
            _ => None,
        };

        let positional_encoding = self.positional_encoding(seq_len, self.d_model);

        Ok(FittedAttentionFeatureExtractor {
            extractor: self.clone(),
            w_q,
            w_k,
            w_v,
            w_o,
            w_a,
            w_b,
            w_v_add,
            w_mult,
            positional_encoding,
            input_shape: (seq_len, d_input),
        })
    }
}

impl Transform<Array2<f64>, Array2<f64>> for FittedAttentionFeatureExtractor {
    fn transform(&self, x: &Array2<f64>) -> SklResult<Array2<f64>> {
        let (seq_len, d_input) = x.dim();

        if (seq_len, d_input) != self.input_shape {
            return Err(SklearsError::InvalidInput(format!(
                "Input shape {:?} does not match fitted shape {:?}",
                (seq_len, d_input), self.input_shape
            )));
        }

        let q = x.dot(&self.w_q);
        let k = x.dot(&self.w_k);
        let v = x.dot(&self.w_v);

        let q_with_pos = &q + &self.positional_encoding.slice(s![..seq_len, ..]);
        let k_with_pos = &k + &self.positional_encoding.slice(s![..seq_len, ..]);

        let attention_output = match self.extractor.attention_type {
            AttentionType::Scaled => {
                self.extractor.scaled_dot_product_attention(&q_with_pos, &k_with_pos, &v)
            },
            AttentionType::Additive => {
                let w_a = self.w_a.as_ref().expect("operation should succeed");
                let w_b = self.w_b.as_ref().expect("operation should succeed");
                let w_v_add = self.w_v_add.as_ref().expect("operation should succeed");
                self.extractor.additive_attention(&q_with_pos, &k_with_pos, &v, w_a, w_b, w_v_add)
            },
            AttentionType::Multiplicative => {
                let w_mult = self.w_mult.as_ref().expect("operation should succeed");
                self.extractor.multiplicative_attention(&q_with_pos, &k_with_pos, &v, w_mult)
            },
            AttentionType::MultiHead => {
                self.extractor.multi_head_attention(&q_with_pos, &k_with_pos, &v, &self.w_q, &self.w_k, &self.w_v, &self.w_o)
            },
        };

        let dropout_output = self.extractor.apply_dropout(&attention_output);
        let normalized_output = self.extractor.layer_normalize(&dropout_output);

        Ok(normalized_output)
    }
}

impl FittedAttentionFeatureExtractor {
    pub fn get_attention_weights(&self, x: &Array2<f64>) -> SklResult<Array2<f64>> {
        let (seq_len, d_input) = x.dim();

        if (seq_len, d_input) != self.input_shape {
            return Err(SklearsError::InvalidInput("Input shape mismatch".to_string()));
        }

        let q = x.dot(&self.w_q);
        let k = x.dot(&self.w_k);

        let q_with_pos = &q + &self.positional_encoding.slice(s![..seq_len, ..]);
        let k_with_pos = &k + &self.positional_encoding.slice(s![..seq_len, ..]);

        let d_k = k_with_pos.ncols() as f64;
        let scores = q_with_pos.dot(&k_with_pos.t()) / (d_k.sqrt() * self.extractor.temperature);

        Ok(self.extractor.apply_softmax_2d(&scores))
    }

    pub fn get_positional_encoding(&self) -> &Array2<f64> {
        &self.positional_encoding
    }

    pub fn get_output_shape(&self) -> (usize, usize) {
        (self.input_shape.0, self.extractor.d_model)
    }
}