一个明显的问题是,你是截断你的数据文件,当你打开它,因为你是指定写入模式"w"
。这意味着将不会有数据可读。
无论如何,如果您的数据文件与此example中的文件类似,则不需要读取该文件,您需要导入它,因为它是一个python文件。这应该工作:
import svmlight
from data import train0 as training_data # assuming your data file is named data.py
# or you could use __import__()
#training_data = __import__('data').train0
model = svmlight.learn(training_data, type='classification', verbosity=0)
您可能想比较您的数据与示例。
编辑后的数据文件格式澄清
输入文件需要被解析成这样的元组的列表:
[(target, [(feature_1, value_1), (feature_2, value_2), ... (feature_n, value_n)]),
(target, [(feature_1, value_1), (feature_2, value_2), ... (feature_n, value_n)]),
...
]
的svmlight包装似乎并不支持读取一个SVM文件格式的文件,并且没有任何解析函数,所以它必须在Python中实现。 SVM文件看起来是这样的:
<target> <feature>:<value> <feature>:<value> ... <feature>:<value> # <info>
所以这里是从文件格式转换成由svmlight包所需的解析器:
def svm_parse(filename):
def _convert(t):
"""Convert feature and value to appropriate types"""
return (int(t[0]), float(t[1]))
with open(filename) as f:
for line in f:
line = line.strip()
if not line.startswith('#'):
line = line.split('#')[0].strip() # remove any trailing comment
data = line.split()
target = float(data[0])
features = [_convert(feature.split(':')) for feature in data[1:]]
yield (target, features)
而且你可以使用它像这样:
import svmlight
training_data = list(svm_parse('thedata'))
model=svmlight.learn(training_data, type='classification', verbosity=0)
你会得到什么错误?有没有可以发布的回溯? – mhawke 2014-09-04 12:44:04