相关文章推荐
酒量小的滑板  ·  PDF to Excel ...·  8 月前    · 
细心的荒野  ·  基于Verilog ...·  1 年前    · 
气势凌人的牛腩  ·  如何在 JavaScript ...·  1 年前    · 
def random_sample ( array , size : int , replace = True ) : """随机抽样: 每个样本等概率抽样 :param array: 待采样数组 :param size: 采样个数 :param replace: 是否放回,True为有放回的抽样,False为无放回的抽样 return np . random . choice ( array , size = size , replace = replace ) def cluster_sample ( array ) : """聚类抽样: 也称整群抽样,先对样本聚出多个类,然后随机的抽类,抽中哪个类,这一类的所有样本点都会被抽出来,不会对单个点进行抽样 :param array: 样本点 from sklearn . cluster import DBSCAN label = DBSCAN ( eps = 30 , min_samples = 3 ) . fit ( array ) . labels_ # 使用DBSCAN做聚类,这个可以换 select_cluster = random_sample ( np . unique ( label ) , 1 ) # 随机选择一个类 return array [ label == select_cluster ] def systematic_sample ( array , step ) : """系统抽样: 以固定的节奏从总体中抽样,隔step个抽1个,再隔step个抽一个,循环下去 :param array: 样本点 :param step: 步长 select_index = list ( range ( 0 , len ( array ) , 3 ) ) return array [ select_index ] def stratify_sample ( array , label , size : int ) : """分层抽样: 先按照容量,给每个样本一些指标,然后样本内等概率抽样 :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 并没有专有的 抽样 方法 库,所以将自己以前的笔记汇总到自写库中,用到时直接调用函数即可,快速且精确。   全部源 代码 (根据填入参数选择不同的 抽样 方法 ) --》 对每一 方法 进行单独 使用 并附上效果图 全部源 代码 (含注释) # -----------------...