[英]Creating a COO matrix from a 2D numpy array
我有一個2D numpy數組,看起來像這樣,
[[3, 4, 5, 6], [4, 5, 6, 7], [9, 10, 3, 5]]
我使用以下代碼將其轉換為COO矩陣:
# Flatten 2D array
data = np.asarray(twod_array).flatten()
row = np.arange(0, len(data))
col = np.arange(0, len(row))
# Make COO matrix
mat = coo_matrix((data, (row, col)), shape=(len(row), len(row)))
這是將2D numpy數組轉換為COO矩陣的正確方法嗎?
編輯
我想要做的就是這個,我有一個coloumn和另一個項目的部分。
parts item
processor, display, sensor temp. monitoring system
fan baldes, motor, sensor motion detecting fan
. .
. .
我已將上面的數據轉換為數字,以便進一步處理。
parts items
1, 2, 3 1
4, 5, 3 2
所以現在,我想將上述數據提供給LightFM,所以我創建了一個像這樣的2D數組。
[[1, 2, 3, 1], [4, 5, 3, 2]]
但是因為LightFM的fit方法只接受形狀[n_users,n_items]的np.float32 coo_matrix,這是一個包含用戶項交互的矩陣。 我使用上述方法轉換了2D陣列。
In [301]: A = np.array([[3, 4, 5, 6], [4, 5, 6, 7], [9, 10, 3, 5]])
In [302]: A
Out[302]:
array([[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 9, 10, 3, 5]])
你創建矩陣的方式:
In [305]: data =A.flatten()
In [306]: M = sparse.coo_matrix((data,(np.arange(len(data)),np.arange(len(data))
...: )))
In [307]: M
Out[307]:
<12x12 sparse matrix of type '<class 'numpy.int32'>'
with 12 stored elements in COOrdinate format>
print(M)
將用它們的坐標顯示這12個值。
如果它不是太大我喜歡將矩陣顯示為數組。 MA
是M.toarray()
:
In [308]: M.A
Out[308]:
array([[ 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]])
看對角線 - 這是原始數組的12個值。 那是你要的嗎? A
的原始3x4布局完全丟失。 它可能也是這12個數字的1d列表。
或者,您可以將數組傳遞給稀疏構造函數,從而生成原始的稀疏副本
In [309]: M1 = sparse.coo_matrix(A)
In [310]: M1
Out[310]:
<3x4 sparse matrix of type '<class 'numpy.int32'>'
with 12 stored elements in COOrdinate format>
In [311]: M1.A
Out[311]:
array([[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 9, 10, 3, 5]])
而不是12x12對角線,這是一個沒有任何0的3x4陣列。 如果A
已經有很多0,這就更有意義了。
你真的知道你需要什么樣的稀疏矩陣嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.