使用Python将CSV文件转换为LIBSVM兼容数据文件

6 投票
2 回答
15974 浏览
提问于 2025-04-18 03:23

我正在做一个项目,使用libsvm这个库,现在我需要准备我的数据,想知道怎么把CSV文件转换成libsvm能用的数据格式。

CSV文件: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/data/iris.csv

关于频率的问题:

怎么把其他数据格式转换成LIBSVM格式?

这要看你的数据格式。一个简单的方法是使用libsvmwrite这个函数,在libsvm的matlab/octave接口中。以UCI机器学习库中的CSV(逗号分隔值)文件为例。我们下载SPECTF.train文件。标签在第一列。接下来的步骤可以生成一个libsvm格式的文件。

matlab> SPECTF = csvread('SPECTF.train'); % read a csv file
matlab> labels = SPECTF(:, 1); % labels from the 1st column
matlab> features = SPECTF(:, 2:end); 
matlab> features_sparse = sparse(features); % features must be in a sparse matrix
matlab> libsvmwrite('SPECTFlibsvm.train', labels, features_sparse);
The tranformed data are stored in SPECTFlibsvm.train.
Alternatively, you can use convert.c to convert CSV format to libsvm format.

但是我不想用matlab,我用的是python。

我还找到了一种用JAVA的方法。

有没有人能推荐一个解决这个问题的方法?

2 个回答

5

csv2libsvm.py 这个文件在Python3中无法使用,而且它也不支持标签目标(字符串目标)。我对它做了一些小改动。现在它应该可以在Python3中正常工作,并且支持标签目标。
我对Python还很陌生,所以我的代码可能不太符合最佳实践,但我希望它能对某些人有所帮助。

#!/usr/bin/env python

"""
Convert CSV file to libsvm format. Works only with numeric variables.
Put -1 as label index (argv[3]) if there are no labels in your file.
Expecting no headers. If present, headers can be skipped with argv[4] == 1.

"""

import sys
import csv
import operator
from collections import defaultdict

def construct_line(label, line, labels_dict):
    new_line = []
    if label.isnumeric():
        if float(label) == 0.0:
            label = "0"
    else:
        if label in labels_dict:
            new_line.append(labels_dict.get(label))
        else:
            label_id = str(len(labels_dict))
            labels_dict[label] = label_id
            new_line.append(label_id)

    for i, item in enumerate(line):
        if item == '' or float(item) == 0.0:
            continue
        elif item=='NaN':
            item="0.0"
        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]
try:
    output_file = sys.argv[2]
except IndexError:
    output_file = input_file+".out"


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, 'rt')
o = open(output_file, 'wb')

reader = csv.reader(i)

if skip_headers:
    headers = reader.__next__()

labels_dict = {}
for line in reader:
    if label_index == -1:
        label = '1'
    else:
        label = line.pop(label_index)

    new_line = construct_line(label, line, labels_dict)
    o.write(new_line.encode('utf-8'))
7

你可以使用 csv2libsvm.py 这个工具,把 csv 格式的数据转换成 libsvm data 格式。

python csv2libsvm.py iris.csv libsvm.data 4 True

这里的4代表 target index,而 True 表示 csv 文件里有表头。

最后,你可以得到 libsvm.data 文件,内容如下:

0 1:5.1 2:3.5 3:1.4 4:0.2
0 1:4.9 2:3.0 3:1.4 4:0.2
0 1:4.7 2:3.2 3:1.3 4:0.2
0 1:4.6 2:3.1 3:1.5 4:0.2
...

数据来源于 iris.csv 文件。

150,4,setosa,versicolor,virginica
5.1,3.5,1.4,0.2,0
4.9,3.0,1.4,0.2,0
4.7,3.2,1.3,0.2,0
4.6,3.1,1.5,0.2,0
...

撰写回答