gpt4 book ai didi

c++ - 将数据抽样为两组

转载 作者:行者123 更新时间:2023-11-28 07:30:48 25 4
gpt4 key购买 nike

我正在寻求帮助以提高下面的代码效率。虽然它有效,但我不满意。有 bug 需要修复(目前无关紧要)。我第一次使用 header ,第一次使用 stable_partition。

问题定义/规范:
我有一个数字数据(浮点值)的总体( vector )。我想根据用户指定的百分比创建两个随机样本(2 个 vector )。即 popu_data = 30%Sample1 + 70%Sample2 - 这里的 30% 将由用户给出。我还没有实现 % 但它微不足道。

编程中的问题:我能够从总体中创建 30% 的样本。创建另一个 vector (sample2 - 70%) 的第二部分是我的问题。原因是在选择 30% 数据时,我必须随机选择值。我必须跟踪索引以删除它们。但是有些我没有得到比我实现的逻辑更有效的逻辑。

我的逻辑是(不高兴):在人口数据中,随机索引处的值被替换为唯一值(此处为 0.5555)。后来我了解了 stable_partition 函数,其中将 Population 的各个值与 0.5555 进行比较。如果为 false,则该数据创建为补充 sample1 的新 Sample2。

此外:我怎样才能使这个通用的,即人口分成用户定义的人口百分比的 N 个子样本。

感谢您的帮助。我尝试了 vector 删除、删除、复制等,但它没有实现为当前代码。我正在寻找更好、更高效的逻辑和 STL 用法。

#include <random>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool Is05555 (float i){
if ( i > 0.5560 ) return true;
return false;
}

int main()
{
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(1, 2);
vector<float>randVals;

cout<<"All the Random Values between 1 and 2"<<endl;
for (int n = 0; n < 20; ++n) {
float rnv = dis(gen);
cout<<rnv<<endl;
randVals.push_back(rnv);
}
cout << '\n';

random_device rd2;
mt19937 gen2(rd2());
uniform_int_distribution<int> dist(0,19);

vector<float>sample;
vector<float>sample2;
for (int n = 0; n < 6; ++n) {
float rnv = dist(gen2);
sample.push_back(randVals.at(rnv));
randVals.at(rnv) = 0.5555;
}

cout<<"Random Values between 1 and 2 with 0.5555 a Unique VAlue"<<endl;
for (int n = 0; n < 20; ++n) {
cout<<randVals.at(n)<<" ";
}
cout << '\n';

std::vector<float>::iterator bound;
bound = std::stable_partition (randVals.begin(), randVals.end(), Is05555);

for (std::vector<float>::iterator it=randVals.begin(); it!=bound; ++it)
sample2.push_back(*it);

cout<<sample.size()<<","<<sample2.size()<<endl;

cout<<"Random Values between 1 and 2 Subset of 6 only: "<<endl;

for (int n = 0; n < sample.size(); ++n) {
cout<<sample.at(n)<<" ";
}
cout << '\n';

cout<<"Random Values between 1 and 2 - Remaining: "<<endl;
for (int n = 0; n < sample2.size(); ++n) {
cout<<sample2.at(n)<<" ";
}
cout << '\n';

return 0;
}

最佳答案

给定 N% 样本的要求,与顺序无关,最简单的做法可能是:

std::random_shuffle(randVals.begin(), randVals.end());
int num = randVals.size() * percent / 100.0;

auto pos = randVals.begin() + randVals.size() - num;

// get our sample
auto sample1{pos, randVals.end()};

// remove sample from original collection
randVals.erase(pos, randVals.end());

对于数组中的某些类型的项目,您可以通过将项目从原始数组移动到样本数组来改进这一点,但对于像 floatdouble 这样的简单类型,那不会完成任何事情。

关于c++ - 将数据抽样为两组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com