python – 来自熊猫的分层样本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 来自熊猫的分层样本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2170字,纯文字阅读大概需要4分钟。
内容图文
![python – 来自熊猫的分层样本](/upload/InfoBanner/zyjiaocheng/697/ee8cf76a5b3f4fbe85f056ea093c23c8.jpg)
我有一个pandas DataFrame,看起来大致如下:
cli_id | X1 | X2 | X3 | ... | Xn | Y |
----------------------------------------
123 | 1 | A | XX | ... | 4 | 0.1 |
456 | 2 | B | XY | ... | 5 | 0.2 |
789 | 1 | B | XY | ... | 5 | 0.3 |
101 | 2 | A | XX | ... | 4 | 0.1 |
...
我有客户端ID,很少有分类属性,Y是事件的概率,其值从0到1乘以0.1.
我需要在每个组(10倍)的大小为200的Y中采取分层样本
在分成火车/测试时,我经常使用它来分层样本:
def stratifiedSplit(X,y,size):
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=size, random_state=0)
for train_index, test_index in sss:
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
return X_train, X_test, y_train, y_test
但在这种情况下我不知道如何修改它.
解决方法:
我不完全确定你的意思是:
strats = []
for k in range(11):
y_val = k*0.1
dummy_df = your_df[your_df['Y'] == y_val]
stats.append( dummy_df.sample(200) )
这使得虚拟数据帧仅包含您想要的Y值,然后采样200.
好的,所以你需要不同的块来拥有相同的结构.我想这有点难,我就是这样做的:
首先,我会得到X1的直方图:
hist, edges = np.histogram(your_df['X1'], bins=np.linespace(min_x, max_x, nbins))
我们现在有一个带有nbins箱的直方图.
现在的策略是根据X1的值来绘制一定数量的行.我们将从具有更多观察值的箱子中抽取更多,并且从更少的箱子中抽取更多,从而保留X的结构.
特别是,每个垃圾箱的相对贡献应该是:
rel = [float(i) / sum(hist) for i in hist]
这将是[0.1,0.2,0.1,0.3,0.3]
如果我们想要200个样本,我们需要绘制:
draws_in_bin = [int(i*200) for i in rel]
现在我们知道从每个箱子中抽取多少观察:
strats = []
for k in range(11):
y_val = k*0.1
#get a dataframe for every value of Y
dummy_df = your_df[your_df['Y'] == y_val]
bin_strat = []
for left_edge, right_edge, n_draws in zip(edges[:-1], edges[1:], draws_in_bin):
bin_df = dummy_df[ (dummy_df['X1']> left_edge)
& (dummy_df['X1']< right_edge) ]
bin_strat.append(bin_df.sample(n_draws))
# this takes the right number of draws out
# of the X1 bin where we currently are
# Note that every element of bin_strat is a dataframe
# with a number of entries that corresponds to the
# structure of draws_in_bin
#
#concatenate the dataframes for every bin and append to the list
strats.append( pd.concat(bin_strat) )
内容总结
以上是互联网集市为您收集整理的python – 来自熊猫的分层样本全部内容,希望文章能够帮你解决python – 来自熊猫的分层样本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。