私はこのようになりますsparse.txtがあります。必要なdense.txtはこれです(numpyの/ scipyのダウンロードが、NO sklearn)efficentlyスパース行列から密行列を作成していない
# 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
を:
# 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'))
それは動作しませんでした!
関連リンク:
Parsing colon separated sparse data with pandas and numpy(明示的sklearnを禁止する前に回答)
リストで '行 'を収集するのはどうですか?それはリスト(数字のリスト)でしょうか?あなたはそれから直接配列を作ることができますか? – hpaulj
@hpaulj、私はラベルの配列を作ることができますが、行列を作るのが難しいです。 – astro123
@hpauj、私もnumpy.loadtxt、 – astro123