|
| 1 | +extern crate lightgbm; |
| 2 | +extern crate csv; |
| 3 | +extern crate serde_json; |
| 4 | +extern crate itertools; |
| 5 | + |
| 6 | + |
| 7 | +use itertools::zip; |
| 8 | +use lightgbm::{Dataset, Booster}; |
| 9 | +use serde_json::json; |
| 10 | + |
| 11 | + |
| 12 | +fn load_file(file_path: &str) -> (Vec<Vec<f64>>, Vec<f32>) { |
| 13 | + let rdr = csv::ReaderBuilder::new().has_headers(false).delimiter(b'\t').from_path(file_path); |
| 14 | + let mut labels: Vec<f32> = Vec::new(); |
| 15 | + let mut features: Vec<Vec<f64>> = Vec::new(); |
| 16 | + for result in rdr.unwrap().records() { |
| 17 | + let record = result.unwrap(); |
| 18 | + let label = record[0].parse::<f32>().unwrap(); |
| 19 | + let feature: Vec<f64> = record.iter().map(|x| x.parse::<f64>().unwrap()).collect::<Vec<f64>>()[1..].to_vec(); |
| 20 | + labels.push(label); |
| 21 | + features.push(feature); |
| 22 | + } |
| 23 | + (features, labels) |
| 24 | +} |
| 25 | + |
| 26 | +fn argmax<T: PartialOrd>(xs: &[T]) -> usize { |
| 27 | + if xs.len() == 1 { |
| 28 | + 0 |
| 29 | + } else { |
| 30 | + let mut maxval = &xs[0]; |
| 31 | + let mut max_ixs: Vec<usize> = vec![0]; |
| 32 | + for (i, x) in xs.iter().enumerate().skip(1) { |
| 33 | + if x > maxval { |
| 34 | + maxval = x; |
| 35 | + max_ixs = vec![i]; |
| 36 | + } else if x == maxval { |
| 37 | + max_ixs.push(i); |
| 38 | + } |
| 39 | + } |
| 40 | + max_ixs[0] |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +fn main() -> std::io::Result<()> { |
| 45 | + let (train_features, train_labels) = load_file("../../lightgbm-sys/lightgbm/examples/multiclass_classification/multiclass.train"); |
| 46 | + let (test_features, test_labels) = load_file("../../lightgbm-sys/lightgbm/examples/multiclass_classification/multiclass.test"); |
| 47 | + let train_dataset = Dataset::from_mat(train_features, train_labels).unwrap(); |
| 48 | + |
| 49 | + let params = json!{ |
| 50 | + { |
| 51 | + "num_iterations": 100, |
| 52 | + "objective": "multiclass", |
| 53 | + "metric": "multi_logloss", |
| 54 | + "num_class": 5, |
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + let booster = Booster::train(train_dataset, ¶ms).unwrap(); |
| 59 | + let result = booster.predict(test_features).unwrap(); |
| 60 | + |
| 61 | + |
| 62 | + let mut tp = 0; |
| 63 | + for (label, pred) in zip(&test_labels, &result){ |
| 64 | + let argmax_pred = argmax(&pred); |
| 65 | + if *label == argmax_pred as f32 { |
| 66 | + tp = tp + 1; |
| 67 | + } |
| 68 | + println!("{}, {}, {:?}", label, argmax_pred, &pred); |
| 69 | + } |
| 70 | + println!("{} / {}", &tp, result.len()); |
| 71 | + Ok(()) |
| 72 | +} |
0 commit comments