Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python program to export numpy/lists in svmlight format

Any way to export a python array into SVM light format?

like image 829
tomas Avatar asked Feb 15 '12 20:02

tomas


2 Answers

There is one in scikit-learn:

http://scikit-learn.org/stable/modules/generated/sklearn.datasets.dump_svmlight_file.html

It's basic but it works both for numpy arrays and scipy.sparse matrices.

like image 164
ogrisel Avatar answered Sep 28 '22 00:09

ogrisel


I wrote this totally un-optimized script a while ago, maybe it can help! Data and labels must be in two separate numpy arrays.

def save_svmlight_data(data, labels, data_filename, data_folder = ''):
    file = open(data_folder+data_filename,'w')

    for i,x in enumerate(data):
        indexes = x.nonzero()[0]
        values = x[indexes]

        label = '%i'%(labels[i])
        pairs = ['%i:%f'%(indexes[i]+1,values[i]) for i in xrange(len(indexes))]

        sep_line = [label]
        sep_line.extend(pairs)
        sep_line.append('\n')

        line = ' '.join(sep_line)

        file.write(line)
like image 41
levesque Avatar answered Sep 28 '22 01:09

levesque