Libtorch how to generate random within 0-1?

Say this one:

    at::Tensor scores = torch::randn({34}, torch::kCUDA);

I want score actually between 0-1. how to specific this?

it generates -1-1 now.

Try this.
Not recommended…

at::Tensor scores = torch::randn({ 34 }).clamp_max_(1).clamp_min_(0);

Note that randn draws from a unit normal (Gaussian) distribution! It will also not be between -1,1 but just be in ~70% of all cases in this range.

torch::rand or torch.rand (without the trailing n) is for uniform distributed random numbers between 0…1

This generates i.i.d. uniform random numbers between 0 and 1.

#include <torch/torch.h>
#include <iostream>

int main(){
        torch::Tensor tensor = torch::rand({10});
        std::cout<< "Tensor " << tensor << std::endl;
        return 0;
}

1 Like