[Python] Simulate data for binary classification in Rust, as Polars DataFrame/Series...

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to translate the following Python code into Rust/Polars. The code creates a dataset for a binary classification: a response variable with values 0/1 and a set of features for every sample with values in the range [0.,1.).

    import numpy as np
    import pandas as pd

    nsmpls = 50
    nfeats = 10
    smpls_names = [f'smpl{n}' for n in range(nsmpls)]
    feats_names = [f'feat{n}' for n in range(nfeats)]

    #response variable
    y = np.random.randint(0, 2, size=nsmpls)
    y = pd.Series(y, index=smpls_names)

    #data
    X = np.random.random((nfeats, nsmpls))
    X = pd.DataFrame(X, columns=smpls_names, index=feats_names)


    So far I have managed to create a column of integers for the response variable and a single column of features:

    use rand::Rng;
    use polars::prelude::*;

    fn main() {
    let nsmpls = 50;
    let nfeats=10;

    let mut rng = rand::rng();
    //unsuccessful attempt at generating sample names
    // let smpls_names: Vec<String> = (0..nsmpls).map(|v| "{v}").collect();

    //generating response variables
    let y: Series = (0..nsmpls).map(|_| (rng.random_bool(0.5) as u32)).collect();

    //generating a column of features
    let feats_col: Vec<f64> = (0..nsmpls).map(|_| rng.random()).collect();
    }


    However, I am less successful in

    • creating generic sample and feature names (commented line)
    • generating required number of generic columns into a DataFrame (which is partially related to the previous issue)

    Advice or code suggestions will be greatly appreciated.

    Related:
    I took some inspiration from this thread: How do I generate a vector of random numbers in a range?

    Update
    The suggested duplicate only partially answers the question. Indeed, by now I have already overcome this issue, but it still remains to generate a DataFrame with an arbitrary number of columns. Here is my current code:

    use rand::Rng;
    use polars::prelude::*;

    fn main() {
    let nsmpls = 50;
    let nfeats=10;

    let mut rng = rand::rng();
    //unsuccessful attempt at generating sample names
    let smpls_names: Vec<String> = (0..nsmpls).map(|v| format!("smpl{v}")).collect();
    let feats_names: Vec<String> = (0..nfeats).map(|v| format!("feat{v}")).collect();

    //generating response variables
    let status: Vec<u32> = (0..nsmpls).map(|_| (rng.random_bool(0.5) as u32)).collect();
    let c1 = Column::new("Sample".into(), &smpls_names);
    let c2 = Column::new("status".into(), &status);
    let y = DataFrame::new(vec![c1, c2]);

    //generating a column of features
    let feats_col: Vec<f64> = (0..nsmpls).map(|_| rng.random()).collect();
    }

    Continue reading...

Compartilhe esta Página