How can I convert a Vector to Tensor?
              
              #1353
            
            
              
                
                  
                  
                    Answered
                  
                  by
                    laggui
                  
              
          
                  
                    
                      zemelLeong
                    
                  
                
                  asked this question in
                Q&A
              
            -
        impl<B: Backend> PositionalEncoder<B> {
    pub fn new(
        d_model: usize,
        max_seq_len: Option<usize>,
        dropout: Option<f64>,
        device: &B::Device,
    ) -> Self {
        let max_seq_len = max_seq_len.unwrap_or(900);
        // let mut pe = Tensor::zeros([max_seq_len, d_model], device);
        let mut pe = vec![vec![0.0; d_model]; max_seq_len];
        for pos in 0..max_seq_len {
            for i in (0..d_model).step_by(2) {
                let sin_coef = (10000.0_f64).powf((2 * i) as f64 / d_model as f64);
                let cos_coef = (10000.0_f64).powf((2 * (i + 1)) as f64 / d_model as f64);
                pe[pos][i] = (pos as f64 / sin_coef).sin();
                pe[pos][i + 1] = (pos as f64 / cos_coef).cos();
            }
        }
        let pe = Tensor::<B, 2>::from_data(Data::from(pe), device);
        let pe = pe.unsqueeze();
        let dropout = DropoutConfig::new(dropout.unwrap_or(0.1)).init();
        Self {
            d_model,
            dropout,
            pe,
        }
    }
} | 
  
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            laggui
          
      
      
        Feb 23, 2024 
      
    
    Replies: 1 comment 2 replies
-
| 
         It was already answered on discord but will provide an example here for future reference. You can use  For example, you can convert an image vector to tensor: // Here img_vec is a Vec<u8> for an image with shape 224x224x3
Tensor::<B, 3>::from_data(Data::new(img_vec, Shape::new(224, 224, 3)).convert(), device) | 
  
Beta Was this translation helpful? Give feedback.
                  
                    2 replies
                  
                
            
      Answer selected by
        antimora
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
It was already answered on discord but will provide an example here for future reference. You can use
Data::newwithShapeto create a new tensor.For example, you can convert an image vector to tensor: