最近要做SVM分类,使用libsvm,需要将excel的数据转化到libsvm格式下。
libsvm数据格式如下:(第一列是labels,后面是依次的features,空缺表示null)
+1 4:-0.320755
-1 1:0.583333 2:-1 3:0.333333
+1 1:0.166667 2:1 3:-0.333333 4:-0.433962
-1 1:0.458333 3:1 4:-0.358491
网上查了一下,发现都是用
FormatDataLibsvm.xls
这个文件的,但是又找不到这个文件,就自己python写了一个,需要用的而且自己不想写的就拿去用吧。
##
# create by zhenyuxiaoge on 2016/11/25
##
# transform data.txt to libsvm type data, get libsvm.txt
#read data file
readin = open('data.txt', 'r')
#write data file
output = open('libsvm.txt', 'w')
try:
the_line = readin.readline()
while the_line:
# delete the \n
the_line = the_line.strip('\n')
index = 0;
output_line = ''
for sub_line in the_line.split('\t'):
#the label col
if index == 0:
output_line = sub_line
#the features cols
if sub_line != 'NULL' and index != 0:
the_text = ' ' + str(index) + ':' + sub_line
output_line = output_line + the_text
index = index + 1
output_line = output_line + '\n'
output.write(output_line)
the_line = readin.readline()
finally:
readin.close()
代码比较简单,就直接复制好了,相应的地方可以自己改动一下。这边是第一列默认是label,空值为大写的NULL。
版权声明:本文为zhenyuxiaoge原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。