Z
Z
ziplane2019-09-07 13:11:27
Rust
ziplane, 2019-09-07 13:11:27

Why is u8 not converting to f32 or how to read string in f32?

Good day!
I created a csv file and wanted to read its contents.

1,0,0,0,0,0
2,0,0,0,0,0

To do this, I created the MNIST structure
pub struct MNIST {
   pub labels:Vec<u8>,
   pub num_img:Vec<u8>
}

Reading a file with this method
pub fn read(&mut self, path:&str)  {
        let mut file = File::open(path).expect("err from ...");
        let mut reader = BufReader::new(file);
        let mut buf:Vec<u8> = Vec::new();
        let ra:u8 = 44; //  44 это запятая )))
        // читать  строку. затем первый элемент закинуть в labels остальное в num
        while reader.read_until(b'\n',&mut buf).expect("err from ...") != 0 {
            self.labels.push(buf[0]);
            for (i,v) in buf.iter().enumerate(){
                // если элемент не первый и не является запятой
                if i >0 && *v != ra  {self.num_img.push(*v)}
            }
            buf.clear();
        }
        
    }

Then I change the type to f32 but something goes wrong
pub fn get_labels(&self,out_lbl:usize,min:f32,tr:f32) -> Vec<Vec<f32>>{

        let mut labels:Vec<Vec<f32>> = Vec::new();
        let mut buf:Vec<f32> = Vec::new();

        // Заполняем labels
        for v in &self.labels {

            for j in 0..out_lbl {
                if *v as usize == j { buf.push(tr)} else {buf.push(*v as f32)  }
            }

            labels.push(buf.clone());
            buf.clear();
        }
        labels
    }

and I get this
instead of 1 - 49,
2 - 50,
0 - 48,
instead of a comma - 44

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
ziplane, 2019-09-19
@ziplane

Searching, I found a way only with strings. In short, we read a string and cast it to a number. I decided to go in a different perverted way.

pub fn get_labels(&self,out_lbl:usize,min:f32,max:f32) -> Vec<Vec<f32>>{

        let mut labels:Vec<Vec<f32>> = Vec::new();
        let mut buf:Vec<f32> = Vec::new();

        // Заполняем labels
        for v in &self.labels {

            for j in 1..out_lbl {

                let mut buf_str = *v as char;
                let mut z = buf_str.to_digit(10).unwrap();
                if z as usize == j { buf.push(max)} else {buf.push(min)  }
            }

            labels.push(buf.clone());
            buf.clear();
        }
        labels
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question