有时我们在实际分类数据挖掘中经常会遇到,类别样本很不均衡,直接使用这种不均衡数据会影响一些模型的分类效果,如logistic regression,SVM等,一种解决办法就是对数据进行均衡采样,这里就提供了一个建议代码实现,要求输入和输出数据格式为Label+Tab+Features, 如Libsvm format

-1 1:0.875 2:-1 3:-0.333333 4:-0.509434 5:-0.347032 6:-1 7:1 8:-0.236641 9:1 10:-0.935484 11:-1 12:-0.333333 13:-1
+1 1:0.166667 2:1 3:-0.333333 4:-0.433962 5:-0.383562 6:-1 7:-1 8:0.0687023 9:-1 10:-0.903226 11:-1 12:-1 13:1
+1 1:0.708333 2:1 3:1 4:-0.320755 5:-0.105023 6:-1 7:1 8:-0.419847 9:-1 10:-0.225806 12:1 13:-1
-1 1:0.583333 2:-1 3:0.333333 4:-0.603774 5:1 6:-1 7:1 8:0.358779 9:-1 10:-0.483871 12:-1 13:1

用法 Usage:

Usage: {0} [options] dataset subclass_size [output]
options:
-s method : method of selection (default 0)
0 -- over-sampling & under-sampling given subclass_size
1 -- over-sampling (subclass_size: any value)
2 -- under-sampling(subclass_size: any value)

Bash example:

python SampleDataset.py -s 0 heart_scale 20 heart_scale.txt

这里s参数表示抽样的方法,

-s 0:Over sampling &Under sampling ,即对类别多的进行降采样,对类别少的进行重采样

-s 1: Over sampling 对类别少的进行重采样,采样后的每类样本数与最多的那一类一致

-s 2:Under sampling 对类别多的进行降采样,采样后的每类样本数与最少的那一类一值

输入数据文件heart_scale

输出数据文件heart_scale.txt

下面是代码文件:SampleDataset.py:

#!/usr/bin/env python
from sklearn.datasets import load_svmlight_file
from sklearn.datasets import dump_svmlight_file
import numpy as np
from sklearn.utils import check_random_state
from scipy.sparse import hstack,vstack
import os, sys, math, random
from collections import defaultdict
if sys.version_info[0] >= 3:
xrange = range def exit_with_help(argv):
print("""\
Usage: {0} [options] dataset subclass_size [output]
options:
-s method : method of selection (default 0)
0 -- over-sampling & under-sampling given subclass_size
1 -- over-sampling (subclass_size: any value)
2 -- under-sampling(subclass_size: any value) output : balance set file (optional)
If output is omitted, the subset will be printed on the screen.""".format(argv[0]))
exit(1) def process_options(argv):
argc = len(argv)
if argc < 3:
exit_with_help(argv) # default method is over-sampling & under-sampling
method = 0
BalanceSet_file = sys.stdout i = 1
while i < argc:
if argv[i][0] != "-":
break
if argv[i] == "-s":
i = i + 1
method = int(argv[i])
if method not in [0,1,2]:
print("Unknown selection method {0}".format(method))
exit_with_help(argv)
i = i + 1 dataset = argv[i]
BalanceSet_size = int(argv[i+1]) if i+2 < argc:
BalanceSet_file = open(argv[i+2],'w') return dataset, BalanceSet_size, method, BalanceSet_file def stratified_selection(dataset, subset_size, method):
labels = [line.split(None,1)[0] for line in open(dataset)]
label_linenums = defaultdict(list)
for i, label in enumerate(labels):
label_linenums[label] += [i] l = len(labels)
remaining = subset_size
ret = [] # classes with fewer data are sampled first;
label_list = sorted(label_linenums, key=lambda x: len(label_linenums[x]))
min_class = label_list[0]
maj_class = label_list[-1]
min_class_num = len(label_linenums[min_class])
maj_class_num = len(label_linenums[maj_class])
random_state = check_random_state(42) for label in label_list:
linenums = label_linenums[label]
label_size = len(linenums)
if method == 0:
if label_size<subset_size:
ret += linenums
subnum = subset_size-label_size
else:
subnum = subset_size
ret += [linenums[i] for i in random_state.randint(low=0, high=label_size,size=subnum)]
elif method == 1:
if label == maj_class:
ret += linenums
continue
else:
ret += linenums
subnum = maj_class_num-label_size
ret += [linenums[i] for i in random_state.randint(low=0, high=label_size,size=subnum)]
elif method == 2:
if label == min_class:
ret += linenums
continue
else:
subnum = min_class_num
ret += [linenums[i] for i in random_state.randint(low=0, high=label_size,size=subnum)]
random.shuffle(ret)
return ret def main(argv=sys.argv):
dataset, subset_size, method, subset_file = process_options(argv)
selected_lines = [] selected_lines = stratified_selection(dataset, subset_size,method) #select instances based on selected_lines
dataset = open(dataset,'r')
datalist = dataset.readlines()
for i in selected_lines:
subset_file.write(datalist[i])
subset_file.close() dataset.close() if __name__ == '__main__':
main(sys.argv)

Sample a balance dataset from imbalance dataset and save it(从不平衡数据中抽取平衡数据,并保存)的更多相关文章

  1. Compute Mean Value of Train and Test Dataset of Caltech-256 dataset in matlab code

    Compute Mean Value of Train and Test Dataset of Caltech-256 dataset in matlab code clc;imPath = '/ho ...

  2. XML与DataSet相互转换,DataSet查询

    以FileShare.Read形式读XML文件: string hotspotXmlStr = string.Empty; try { Stream fileStream = new FileStre ...

  3. Spark:几种给Dataset增加列的方式、Dataset删除列、Dataset替换null列

    几种给Dataset增加列的方式 首先创建一个DF对象: scala> spark.version res0: String = .cloudera1 scala> val , , 2.0 ...

  4. 黑马程序员_ADO.Net(ExecuteReader,Sql注入与参数添加,DataSet,总结DataSet与SqlDataReader )

    转自https://blog.csdn.net/u010796875/article/details/17386131 一.执行有多行结果集的用ExecuteReader SqlDateReader  ...

  5. cannot use the same dataset for report.dataset and page.dataset

    把page中的dataset中填的数据表删除.(改成not assigned)

  6. 什么叫强类型的DATASET ?对DATASET的操作处理?强类型DataSet的使用简明教程

    强类型DataSet,是指需要预先定义对应表的各个字段的属性和取值方式的数据集.对于所有这些属性都需要从DataSet, DataTable, DataRow继承,生成相应的用户自定义类.强类型的一个 ...

  7. (原)强类型dataset(类型化dataset)中动态修改查询条件(不确定参数查询)

    原创博客,转载请注明:http://www.cnblogs.com/albert1017/p/3361932.html 查询时有多个参数,参数个数由客户输入决定,不能确定有多少个参数,按一般的方法每种 ...

  8. python概念-常用模块之究竟你是什么鬼

    模块: 一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 说白了,就是一个python文件中定义好了类和方法,实现了一些功能,可以被别的python文件所调用 ...

  9. Spark提高篇——RDD/DataSet/DataFrame(一)

    该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 先来看下官网对RDD.DataSet.DataFrame的解释: 1.RDD ...

随机推荐

  1. If you only do what you can do you'll never be more than you are now.

    If you only do what you can do you'll never be more than you are now. 如果你只是做你力所能及的事,你将不会有所进步:

  2. win7 ins 30131 oracle 12c

    Cause - Failed to access the temporary location. Action - Ensure that the current user has required ...

  3. C语言中关于POW在不同状态下四舍五入的解决方法

    这是今天作业中的一个代码: #include <stdio.h>#include<math.h>int main(){ printf("请输入一个整数:") ...

  4. Mac OSX上的软件包管理工具,brew 即 Homebrew

    brew 即 Homebrew,是Mac OSX上的软件包管理工具,能在Mac中方便的安装软件或者卸载软件, 只需要一个命令, 非常方便. brew类似ubuntu系统下的apt-get的功能. 安装 ...

  5. Git使用指南(3)—— 使用Git命令

    暂存区替换掉工作区 git init git init newrepo 克隆仓库 git clone git clone <repo> git clone <repo> < ...

  6. What's the difference between <b> and <strong>, <i> and <em> in HTML/XHTML? When should you use each?

    ref:http://stackoverflow.com/questions/271743/whats-the-difference-between-b-and-strong-i-and-em The ...

  7. PHP基础结业感想与总结!

    之前来传智是我认真调查和思考后得出的结论,我做程序员的第一目标是赚钱和学习技术,有一句话"艺多不压身".相信班上所有人的目标都是,这一点都不会庸俗,但是各个人的目的就未必一样了.我 ...

  8. 24.Redis2.8主从集群sentinel

    0.集群架构(此处只说两种;本文2种,避免sentinel成为单节点) 第一种: 第二种: 1.下载redis2.8.x版本,2.8.x都是稳定版 redis-2.8.24.tar.gz 2.解压,安 ...

  9. vc6.0如何显示行号以及出现版本不兼容问题

    有时编译时,提示某某行有错,但是要定位到某一行的话,如果在编辑页面能够将行号显示出来,查找也就更方便了,下面我来介绍一下让VC6.0显示行号的方法.   工具/原料   VC6.0.显示行号的插件 方 ...

  10. 在Eclipse中,如何把一个java项目变成web项目

    经常在eclipse中导入web项目时,出现转不了项目类型的问题,导入后就是一个java项目.解决步骤:1.进入项目目录,可看到.project文件,打开.2.找到<natures>... ...