我正在尝试用LibSVM学习一些机器学习。我有一些Excel CSV格式的“testingset.csv”文件的测试数据,但我必须将此数据集转换为能够在LibSVM中工作。我有以下代码但似乎无法转换它:
import sys
import csv
from collections import defaultdict
def construct_line( label, line ):
new_line = []
if float( label ) == 0.0:
label = "0"
new_line.append( label )
for i, item in enumerate( line ):
if item == '' or float( item ) == 0.0:
continue
new_item = "%s:%s" % ( i + 1, item )
new_line.append( new_item )
new_line = " ".join( new_line )
new_line += "\n"
return new_line
# ---
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
label_index = int( sys.argv[3] )
except IndexError:
label_index = 0
try:
skip_headers = sys.argv[4]
except IndexError:
skip_headers = 0
i = open( input_file, 'rb' )
o = open( output_file, 'wb' )
reader = csv.reader( i )
if skip_headers:
headers = reader.next()
for line in reader:
if label_index == -1:
label = '1'
else:
label = line.pop( label_index )
new_line = construct_line( label, line )
o.write( new_line )
答案 0 :(得分:0)
我认为代码是多余的 svm输入文件的格式是
l 1:x 2:y 3:z 4:...
l 1:x 2:y 3:z 4:...
其中l是标签
我认为您可以将输入文件准备为由\ t分隔的txt文件(将文件保存为带有excel的txt)
A B C D
1 l x y z
2 l x y z
...
而不是使用代码
import sys
f=[i.split() for i in open(sys.argv[1]).readlines()
open(sys.argv[1]+'_4libsvm','w').writelines([i[0]+" "+" ".join(pstr(k+1)+":"+j for k,j in enumerate(i[1:])])+"\n" for i in f])
然后执行 python pythonfile.py input1.txt input2.txt ... 它会转换所有的inputfile