python program to export numpy/lists in svmlight f

2019-05-02 00:26发布

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

3条回答
唯我独甜
2楼-- · 2019-05-02 01:05

The svmlight-loader module can load an svmlight file into a numpy array. I don't think anything exists for the other direction, but the module is probably a good starting point for extending its functionality.

查看更多
一纸荒年 Trace。
3楼-- · 2019-05-02 01:12

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.

查看更多
疯言疯语
4楼-- · 2019-05-02 01:17

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)
查看更多
登录 后发表回答