我需要在 Matlab 中加载 LibSVM 模型文件。Python 接口中提供了这样的功能。有人知道这个功能存在吗?
问问题
1940 次
2 回答
2
“要通过 MATLAB 读取数据,可以使用LIBSVM 包中的libsvmread ”
于 2013-01-10T19:25:16.843 回答
0
我编写了一个简单的脚本来将 libsvm 中的文件加载到数据和标签中,而不使用任何 mex 文件。当然它效率不高,但它可以完成工作
file_name = 'real_sim';
fid = fopen(file_name,'r');
num_of_observations = 0;
num_of_features = 0;
num_of_nonzeros = 0;
% First pass: Extract general information
while 1
% Read line
line_str = fgetl(fid);
if ~ischar(line_str)
break;
end
line_str(line_str == ':') = ' ';
% File format: <label> <index1>:<value1> <index2>:<value2> ...
number_list = sscanf(line_str,'%f');
% Find number of rows, columns and nonzeros
feature_indices = 2:2:numel(number_list);
temp_num = max(number_list(feature_indices));
if temp_num > num_of_features
num_of_features = temp_num;
end
num_of_nonzeros = num_of_nonzeros + numel(feature_indices);
num_of_observations = num_of_observations + 1;
end
fclose(fid);
% Second pass: Read into sparse matrix
labels = zeros(num_of_observations,1);
row_indices = zeros(1,num_of_nonzeros);
col_indices = zeros(1,num_of_nonzeros);
val_list = zeros(1,num_of_nonzeros);
pos = 1;
fid = fopen(file_name,'r');
for line_num = 1 : num_of_observations
% Read line
line_str = fgetl(fid);
line_str(line_str == ':') = ' ';
% File format: <label> <index1>:<value1> <index2>:<value2> ...
number_list = sscanf(line_str,'%f');
% Extract data and labels
labels(line_num) = number_list(1);
feature_indices = 2:2:numel(number_list);
value_indices = 3:2:numel(number_list);
first_index = pos;
last_index = pos + numel(feature_indices) - 1;
row_indices(first_index:last_index) = line_num;
col_indices(first_index:last_index) = number_list(feature_indices);
val_list(first_index:last_index) = number_list(value_indices);
pos = pos + numel(feature_indices);
end
fclose(fid);
data = sparse(row_indices,col_indices,val_list,num_of_observations,num_of_features);
clearvars row_indices col_indices val_list line_str
% Convert labels to range 1-N
unique_labels = unique(labels);
num_of_labels = numel(unique_labels);
map_obj = containers.Map(unique_labels,1:num_of_labels); % Hash map
map_func = @(x) map_obj(x);
labels = arrayfun(map_func,labels);
于 2017-01-23T08:18:24.803 回答