【发布时间】:2017-11-14 04:59:08
【问题描述】:
我有一个如下所示的 sparse.txt:
# first column is label 0 or 1
# rest of the data is sparse data
# maximum value in the data is 4, so the future dense matrix will
# have 1+4 = 5 elements in a row
# file: sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 2:1 3:1 4:1
所需的dense.txt是这样的:
# required file: dense.txt
1 1 1 1 0
0 1 0 0 1
1 0 1 1 1
在不使用 scipy coo_matrix 的情况下,它以如下简单的方式完成:
def create_dense(fsparse, fdense,fvocab):
# number of lines in vocab
lvocab = sum(1 for line in open(fvocab))
# create dense file
with open(fsparse) as fi, open(fdense,'w') as fo:
for i, line in enumerate(fi):
words = line.strip('\n').split(':')
words = " ".join(words).split()
label = int(words[0])
indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]
row = [0]* (lvocab+1)
row[0] = label
# use listcomps
row = [ 1 if i in indices else row[i] for i in range(len(row))]
l = " ".join(map(str,row)) + "\n"
fo.write(l)
print('Writing dense matrix line: ', i+1)
问题 我们如何直接从稀疏数据中获取标签和数据,而无需先创建密集矩阵并优先使用 NUMPY /Scipy?
问题: 我们如何使用 numpy.fromregex 读取稀疏数据?
我的尝试是:
def read_file(fsparse):
regex = r'([0-1]\s)([0-9]):(1\s)*([0-9]:1)' + r'\s*\n'
data = np.fromregex(fsparse,regex,dtype=str)
print(data,file=open('dense.txt','w'))
没用!
相关链接:
【问题讨论】:
-
在列表中收集
row怎么样?那将是一个列表(数字),对吧?你能直接用那个做数组吗? -
@hpaulj,我可以制作标签数组,但制作矩阵有困难。
-
@hpauj,我还可以使用 numpy.loadtxt 从文本文件中读取标签和数据,
-
我正在寻找一种使用 SCIPY COO_MATRIX、numpy fromregex 等的方法
标签: python numpy scipy sparse-matrix