"""分层抽样: 先按照容量,给每个样本一些指标,然后样本内等概率抽样
:param array: 样本数据
:param label: 样本类别
:param size: 采样个数
stratified_sample
,
_
=
train_test_split
(
array
,
train_size
=
size
,
stratify
=
label
)
return
stratified_sample
def
main
(
)
:
array_data
=
np
.
arange
(
0
,
100
)
array_label
=
np
.
random
.
random_integers
(
0
,
5
,
size
=
100
)
random_result
=
random_sample
(
array_data
,
5
)
stratify_result
=
stratify_sample
(
array_data
,
array_label
,
80
)
cluster_result
=
cluster_sample
(
np
.
random
.
random_integers
(
0
,
100
,
size
=
(
100
,
5
)
)
)
systematic_result
=
systematic_sample
(
array_data
,
6
)
if
__name__
==
'__main__'
:
main
(
)
#分层
随机抽样
stratified sampling
import xlrd, xlwt, time, random
xl = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\
分层抽样
.xlsx')
xl_sht1 = xl.sheets()[0]
xl_sht1_nrows = xl_sht1.nrows
title = xl_sht1.row_values(0)
#把样本写进列表
在数据分析和
机器学习
中,我们经常需要从给定的样本中进行
随机抽样
。
Python
提供了多种
方法
来执行此操作,下面将介绍其中的几种
方法
。简单
随机抽样
是指从总体中随机地选取一些个体组成样本,每个个体被选中的概率相等。在
Python
中,可以
使用
random.sample()函数实现简单
随机抽样
。例如,从数值列表[1, 2, 3, 4, 5]中随机抽取3个数:
2. 分层
随机抽样
在某些情况下,我们希望从不同层次的群体中进行
抽样
,这就需要用到分层
随机抽样
。在
Python
中,可以
使用
pandas.DataFram
import random
df_credit = pd.read_csv("./train.csv")
print(df_credit["Credit Default"].value_counts())
n_sample=1000
print(pd.__version__)
aa=df_credit.groupby('Credit Default').sample(n=n_sample,replace=True) ## 这个是
抽样
调查在 统计学 与
Python
数据分析/数据挖掘/数据科学 中非常常用,在实际业务中也是高频刚需,而
Python
并没有专有的
抽样
方法
库,所以将自己以前的笔记汇总到自写库中,用到时直接调用函数即可,快速且精确。
全部源
代码
(根据填入参数选择不同的
抽样
方法
) --》 对每一
方法
进行单独
使用
并附上效果图
全部源
代码
(含注释)
# -----------------...