Skip to main content

data_04_to_tensor/
data_04_to_tensor.rs

1//! # data_04 — The output is a normal `matten::Tensor`
2//!
3//! Run: `cargo run -p matten-data --example data_04_to_tensor`
4//!
5//! ## What this shows
6//! The shape and data order of the produced tensor, and that it is an ordinary
7//! core [`matten::Tensor`] you can hand straight to core `matten` operations.
8//!
9//! ## Teaching points
10//! - the shape is `[rows, columns]`;
11//! - the data is **row-major**: row 0's values first, then row 1's, and so on;
12//! - once converted, there is nothing `matten-data`-specific left — it is just a
13//!   `Tensor`, so core reductions like `mean_axis` work directly.
14
15// `matten-data` produces a core tensor; bring the core type into scope to use it.
16use matten::Tensor;
17use matten_data::Table;
18
19fn main() -> Result<(), matten_data::MattenDataError> {
20    let csv = "\
21region,sales,cost
22north,100,40
23south,150,45
24east,120,55";
25
26    let tensor: Tensor = Table::from_csv_str(csv)?
27        .select_columns(["sales", "cost"])?
28        .try_numeric()?
29        .to_tensor()?;
30
31    // [rows, columns] = [3, 2].
32    assert_eq!(tensor.shape(), &[3, 2]);
33
34    // Row-major: [north.sales, north.cost, south.sales, south.cost, ...].
35    assert_eq!(tensor.as_slice(), &[100.0, 40.0, 150.0, 45.0, 120.0, 55.0]);
36
37    // It is a plain Tensor, so core `matten` operations apply. Mean over axis 0
38    // (down the rows) gives the per-column mean: [mean(sales), mean(cost)].
39    let column_means = tensor.mean_axis(0);
40    println!("shape        : {:?}", tensor.shape());
41    println!("column means : {:?}", column_means.as_slice());
42
43    assert_eq!(column_means.shape(), &[2]);
44    assert_eq!(
45        column_means.as_slice(),
46        &[(100.0 + 150.0 + 120.0) / 3.0, (40.0 + 45.0 + 55.0) / 3.0]
47    );
48
49    println!("data_04_to_tensor: OK");
50    Ok(())
51}