将txt文本格式存储的词id表示的数据集存为matlab中的sparse格式
在对文本数据进行聚类的时候,经常会处理超高维的稀疏矩阵。例如进行K-means聚类的时候,特别是短文本聚类,输入往往是
以下sparse_matrix.m以及str2numarray.m便是作以上处理的matlab代码:
sparse_matrix
输入符号说明:
- path txt文件路径,文件存储为词id表示的数据集,一行为一篇文档,词用数值id表示
- row 文档数量
- col 词典大小,词id序号cong1开始
输出符号说明:
- fea 词id表示的超稀疏矩阵
function [ fea ] = sparse_matrix( path, row, col )
fea = sparse(row, col);
file = fopen(path);
line = fgetl(file);
count = 1;
while ischar(line)
array = str2numarray(line);
for i = 1:length(array)
fre = full(fea(count, i));
if fre == 0
fea(count, i) = 1;
else
fea(count, i) = 1 + fre;
end
end
line = fgetl(file);
count = count + 1;
end
fclose(file);
end
str2numarray
输入符号说明:
- line 一篇文档,字符串格式,其中词用数值id表示(id从1开始)
输出符号说明:
- numarray 一篇文档,数值数组格式,对用输入
function [ numarray ] = str2numarray( line )
temp='';
numarray=[];
for i=1:1:length(line)
if line(i)~=' '
temp=[temp,line(i)];
else
if ~isempty(temp)
numarray=[numarray,str2num(temp)];
temp='';
end
end
end
if ~isempty(temp)
numarray=[numarray,str2num(temp)];
end
end
参考: