tch-rs, how to convert tch.Tensor into a rust vec?

118 views Asked by At

I have a tch::Tensor , and I want to convert it to a rust vec, how can I do it?

I tried the following solution , but it does't work

use tch::Tensor;
fn main(){

   let t: Tensor = Tensor::from_slice(&[1.1 ,2.2 ,3.3 ]); 

   let v  = Vec::<f32>::from(t);

}

Can someone give me the solution codes?

Tried as above.

And I search the tch-rs document ,failed to found the api.

1

There are 1 answers

2
kmdreko On BEST ANSWER

Looks like you'll need to use TryFrom since the Tensor loses the static type information:

let v = Vec::<f32>::try_from(t).expect("wrong type of tensor");

NOTE: I'm not sure if this as-written will succeed or fail since you are creating it from a slice of f64 but trying to get it as a Vec of f32. I'm unfamiliar with the library so I don't know if it will do a conversion and I can't test it myself.