我有几个每个100 MB的文件。这些文件的格式如下:
0 1 2 5 8 67 9 122
1 4 5 2 5 8
0 2 1 5 6
.....
(请注意,实际文件中没有添加对齐空格,每个元素之间只有一个空格,添加对齐的目的是美观效果)
每行中的第一个元素是其二进制分类标记,而行中其余部分则是值为1的特征索引。例如,第三行表示该行的第二、第一、第五和第六个特征的值均为1,其余特征的值均为0。
我尝试从每个文件中读取每一行,并使用sparse.coo_matrix创建如下的稀疏矩阵:
for train in train_files:
with open(train) as f:
row = []
col = []
for index, line in enumerate(f):
record = line.rstrip().split(' ')
row = row+[index]*(len(record)-4)
col = col+record[4:]
row = np.array(row)
col = np.array(col)
data = np.array([1]*len(row))
mtx = sparse.coo_matrix((data, (row, col)), shape=(n_row, max_feature))
mmwrite(train+'trans',mtx)
但是这个处理过程非常耗时。我在晚上开始读取数据,然后让电脑在我睡觉后运行,当我醒来时,它仍然没有完成第一个文件!
有什么更好的方法来处理这种类型的数据吗?