使用1和0 C ++创建随机std :: vector

时间:2016-12-05 21:06:27

标签: c++ random stdvector

我想以我设定的比例创建一个随机1和0的向量(在我称之为dropout的程序中)该向量与先前创建的向量CSUM的大小相同。

在MATLAB中它将是

dropout=0.9;
n_elements=size(CSUM)
drpoutmask = (rand(n_elements) > dropout); 

在C ++中我有

size_t elements = Csum.size();
std::vector<float> y(elements);
std::uniform_real_distribution<float> distribution(0.0f, 1.0f); 
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
std::generate_n(y.begin(), elements, generator);
std::vector<int> dropoutmask(elements,0);
float dropout=0.9;

for(int i=0; i<elements; i++)
  {
  if(y.at(i)>dropout)
    {
    dropoutmask.at(i)=1;
    }
  }
}

哪个有效,但对于大型向量非常慢,有更快的方法吗?我是C ++的新手。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:5)

  1. 您确实知道bernoulli distribution,对吗?您可以使用它直接生成整数向量 示例:

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <random>
    
    int main()
    {
        constexpr double dropout = 0.9; // Chance of 0
        constexpr size_t size = 1000;
        std::random_device rd;
        std::mt19937 gen(rd());
        std::bernoulli_distribution dist(1 - dropout); // bernoulli_distribution takes chance of true n constructor
    
        std::vector<int> dropoutmask(size);
        std::generate(dropoutmask.begin(), dropoutmask.end(), [&]{ return dist(gen); });
        size_t ones = std::count(dropoutmask.begin(), dropoutmask.end(), 1);
        std::cout << "vector contains " << ones << " 1's, out of " << size << ". " << ones/double(size) << "%\n";
        std::cout << "vector contains " << size - ones << " 0's, out of " << size << ". " << (size - ones)/double(size) << "%\n";
    }
    

    实例:http://coliru.stacked-crooked.com/a/a160743185ded5c5

  2. 或者,你可以创建一个所需大小的整数向量(这会将所有元素设置为0),将前N个元素设置为1,其中n是(1 - dropout) * size(你说你想要一个比例,不是随机量接近比例)然后随机播放矢量。

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <random>
    
    int main()
    {
        constexpr double dropout = 0.9; // Chance of 0
        constexpr size_t size = 77;
        std::random_device rd;
        std::mt19937 gen(rd());
    
        std::vector<int> dropoutmask(size);
        std::fill_n(dropoutmask.begin(), dropoutmask.size() * (1 - dropout), 1);
        std::shuffle(dropoutmask.begin(), dropoutmask.end(), gen);
    
        size_t ones = std::count(dropoutmask.begin(), dropoutmask.end(), 1);
        std::cout << "vector contains " << ones << " 1's, out of " << size << ". " << ones/double(size) << "%\n";
        std::cout << "vector contains " << size - ones << " 0's, out of " << size << ". " << (size - ones)/double(size) << "%\n";
    
        for (auto i :dropoutmask) {
            std::cout << i << ' ';   
        }
        std::cout << '\n';
    }
    
  3. 实例:http://coliru.stacked-crooked.com/a/0a9dacd7629e1605