获取libsvm格式的数据

#!/usr/bin/python
# -*- coding:utf-8 -*-
#author: by Tong
import sys
import csv
reload(sys)
sys.setdefaultencoding("utf-8")

def setlibsvm():
    readin  = open('data.txt','r')
    output = open("lib_to_svm.txt",'wb')
    try:
        col = 0
        the_line = readin.readline()
        while the_line:
            if col == 0:
                output.write(the_line)
                col = col +1
                the_line = readin.readline()
                continue
            the_line = the_line.strip('\n')
            output_line = ''
            index = 0
            # print the_line.split('\t')
            for sub_line in the_line.split(' '):
                if index == 0 :
                    output_line = sub_line
                if index > 0 and sub_line != '0':
                    output_line += ' '+str(index)+':'+str(sub_line)
                index = index + 1
            output.write(output_line)
            output.write('\n')
            the_line = readin.readline()
    finally:
        readin.close()

if __name__ == "__main__":
    setlibsvm()
数据的格式为:
label feature1 feature2 feature3
其中以空格作为分隔符,其中的代码可以改变
label feature1 feature2 feature3 feature4
1 1:434 2:32 3:2
0 1:323 3:3 4:3
0 2:3 4:3
0 1:23 2:3 3:2 4:1
这是最终的数据格式。好处是对于稀疏的数据能够节省空间。
原数据格式为:
label feature1 feature2 feature3 feature4
1 434 32 2 0
0 323 0 3 3
0 0 3 0 3
0 23 3 2 1
1 3 12 0 55

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想做个自由的人

随缘吧打赏与否还是会坚持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值