Sample a balance dataset from imbalance dataset and save it(从不平衡数据中抽取平衡数据,并保存)
有时我们在实际分类数据挖掘中经常会遇到,类别样本很不均衡,直接使用这种不均衡数据会影响一些模型的分类效果,如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(从不平衡数据中抽取平衡数据,并保存)的更多相关文章
- 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 ...
- XML与DataSet相互转换,DataSet查询
以FileShare.Read形式读XML文件: string hotspotXmlStr = string.Empty; try { Stream fileStream = new FileStre ...
- Spark:几种给Dataset增加列的方式、Dataset删除列、Dataset替换null列
几种给Dataset增加列的方式 首先创建一个DF对象: scala> spark.version res0: String = .cloudera1 scala> val , , 2.0 ...
- 黑马程序员_ADO.Net(ExecuteReader,Sql注入与参数添加,DataSet,总结DataSet与SqlDataReader )
转自https://blog.csdn.net/u010796875/article/details/17386131 一.执行有多行结果集的用ExecuteReader SqlDateReader ...
- cannot use the same dataset for report.dataset and page.dataset
把page中的dataset中填的数据表删除.(改成not assigned)
- 什么叫强类型的DATASET ?对DATASET的操作处理?强类型DataSet的使用简明教程
强类型DataSet,是指需要预先定义对应表的各个字段的属性和取值方式的数据集.对于所有这些属性都需要从DataSet, DataTable, DataRow继承,生成相应的用户自定义类.强类型的一个 ...
- (原)强类型dataset(类型化dataset)中动态修改查询条件(不确定参数查询)
原创博客,转载请注明:http://www.cnblogs.com/albert1017/p/3361932.html 查询时有多个参数,参数个数由客户输入决定,不能确定有多少个参数,按一般的方法每种 ...
- python概念-常用模块之究竟你是什么鬼
模块: 一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 说白了,就是一个python文件中定义好了类和方法,实现了一些功能,可以被别的python文件所调用 ...
- Spark提高篇——RDD/DataSet/DataFrame(一)
该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 先来看下官网对RDD.DataSet.DataFrame的解释: 1.RDD ...
随机推荐
- cookie 的创建 得到 删除
//设置cookie function setCookie(attr,value,time){ if(time){ var newtime=new Date(); newtime.setTime(ne ...
- 【转】Source Insight的Alt + W键不能使用的解决办法
转载地址:http://velep.com/archives/607.html 对于Source Insight 3.5,习惯于使用Alt + W组合键并配合数字键来切换文件窗口,带来无比的便利.但是 ...
- 用eclipse打开已经编译的工程
第一种方法: eciplise------>File------>Import------>General------>Existing Project into Worksp ...
- activiti 中文文档
http://www.mossle.com http://www.mossle.com/docs/activiti/index.html
- Bootstrap Modal 垂直方向加滚动条
原文链接:http://blog.csdn.net/cyh1111/article/details/52960747 背景 使用Bootstrap Modal实现用户资料修改,由于用户信息过多,默认M ...
- [转]Part2: Understanding !PTE, Part2: Flags and Large Pages
http://blogs.msdn.com/b/ntdebugging/archive/2010/04/14/understanding-pte-part2-flags-and-large-pages ...
- 对象-3.py
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #cbcbcb } p.p2 { margin: 0.0px 0 ...
- mysql replace
replace(object, search,replace) 示例:update table set col1 = replace(col1, 'a', 'A'); 将col1字段中的小写a替换成大 ...
- node.js + expres 的安装
一 windows下安装 首先去官网下载msi安装包. 两篇很有参考价值的文章: http://cnodejs.org/topic/4fae80c02e8fb5bc650a8360 http://bl ...
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器
[自己测了下,能兼容各种浏览器,但是读取中文会出现乱码.自己的解决方法是用notepad++把txt文件编码改为utf-8(应该是和浏览器编码保持一致吧?..)] 原文 http://blog.cs ...