回答編集履歴

1

追記

2022/05/26 04:42

投稿

can110
can110

スコア38266

test CHANGED
@@ -1,117 +1,81 @@
1
1
  原因は、`print(count)`同様の出力結果を文字列としてそのまま書き込んでいるからです。
2
2
 
3
-
4
-
5
3
  今一つやりたいことが分かりませんが、疎行列のまま、行列位置と値を`CSV`形式で出力したい場合は
6
-
7
4
  [scipy.io.mmwrite](https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmwrite.html)にて[Matrix Market](http://math.nist.gov/MatrixMarket/formats.html)形式で出力したテキストを中間ファイルとして利用すれば可能です。
8
-
9
-
10
5
 
11
6
  参考:[Dump a sparse matrix into a file](https://stackoverflow.com/questions/6087520/dump-a-sparse-matrix-into-a-file)
12
7
 
13
-
14
-
15
8
  ```Python
16
-
17
9
  from sklearn.feature_extraction.text import CountVectorizer
18
10
 
19
-
20
-
21
11
  # Scikit learnで行う文章の特徴ベクトルの抽出
22
-
23
12
  # http://nonbiri-tereka.hatenablog.com/entry/2015/06/04/070933
24
-
25
13
  cv = CountVectorizer()
26
-
27
14
  data = [
28
-
29
15
  'This is a pen.',
30
-
31
16
  'That is a bot.',
32
-
33
17
  'These are red document and blue document.',
34
-
35
18
  ]
36
-
37
19
  count = cv.fit_transform(data)
38
-
39
20
  print(count)
40
21
 
41
-
42
-
43
22
  # Matrix Marketファイル(.mtx)を中間ファイルとして利用
44
-
45
23
  from scipy import io
46
-
47
24
  io.mmwrite( 'count', count)
48
-
49
25
  with open( 'count.mtx', 'r') as t:
50
-
51
26
  lines = t.read().split('\n')
52
-
53
27
  lines = lines[3:] # 不要な先頭3行を飛ばす
54
-
55
28
  print(lines)
56
-
57
29
  import os
58
-
59
30
  #os.remove('count.mtx') # 不要なので削除
60
31
 
61
-
62
-
63
32
  import csv
64
-
65
33
  with open('count.csv', 'wt',newline='') as f:
66
-
67
34
  writer = csv.writer(f)
68
-
69
35
  for l in lines:
70
-
71
36
  # 1 7 1
72
-
73
37
  dat = l.split()
74
-
75
38
  if len(dat) == 3:
76
-
77
39
  # 行列位置を0オリジンに
78
-
79
40
  dat[0] = int(dat[0]) - 1
80
-
81
41
  dat[1] = int(dat[1]) - 1
82
-
83
42
  writer.writerow(dat)
84
-
85
43
  ```
86
44
 
87
-
88
-
89
45
  出力結果 : count.csv
90
-
46
+ ```
47
+ 0,6,1
48
+ 0,5,1
49
+ 0,10,1
50
+ 1,3,1
51
+ 1,8,1
52
+ 1,5,1
53
+ 2,2,1
54
+ 2,0,1
55
+ 2,4,2
56
+ 2,7,1
57
+ 2,1,1
58
+ 2,9,1
91
59
  ```
92
60
 
61
+ あるいは自力で出力することもできます。
62
+ ```Python
93
- 0,6,1
63
+ # 略
94
64
 
65
+ def to_lines(m):
95
- 0,5,1
66
+ lines = []
67
+ ip = m.indptr
68
+ for x in range(len(ip)-1):
69
+ s,e = ip[x], ip[x+1]
70
+ if s != e:
71
+ for y, v in zip( m.indices[s:e], m.data[s:e]):
72
+ lines.append((x,y,v))
73
+ return lines
96
74
 
97
- 0,10,1
75
+ lines = to_lines(count)
76
+ lines.sort() # 分かりやすいように
98
77
 
78
+ with open('ret.csv', 'w') as f:
99
- 1,3,1
79
+ for l in lines:
100
-
101
- 1,8,1
102
-
103
- 1,5,1
104
-
105
- 2,2,1
106
-
107
- 2,0,1
80
+ f.write(f'{l[0]},{l[1]},{l[2]}\n')
108
-
109
- 2,4,2
110
-
111
- 2,7,1
112
-
113
- 2,1,1
114
-
115
- 2,9,1
116
-
117
81
  ```