将列表转换为二维numpy矩阵

2024-03-28 15:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python列表。清单如下:

[[196, 242, 3], 
 [186, 302, 3], 
 [22, 377, 1],
 [196, 377, 3],
 ....
 ]

第一列对应于用户(1:943),第二列对应于项目(1:1682)及其对项目的投票。我想试试矩阵分解library。我应该创建一个用户x项目矩阵吗?如果是的话,我如何在python中创建一个这样的矩阵,一个轴是用户的大小,另一个轴是项目的大小,值是用户的投票数?你知道吗

编辑:我还检查不高于它需要一个二维矩阵作为输入,而不是一个列表或稀疏表示。你知道吗


Tags: 项目用户编辑列表library矩阵投票投票数
3条回答

当然。你知道吗

可以使用^{}函数创建二维numpy数组(可以将其视为矩阵):

mat = np.array(list_of_lists)

下面是如何从集合项列表创建稀疏矩阵:

data = [
    [196, 242, 3], 
    [186, 302, 3], 
    [22, 377, 1],
    [196, 377, 3],
    ....
]

user_count = max(i[0] for i in data) + 1
item_count = max(i[1] for i in data) + 1

data_mx = scipy.sparse.dok_matrix((user_count, item_count))
for (user, item, value) in data:
    data_mx[user, item] = value

您的数据看起来像一个列表列表:

In [168]: ll = [[196, 242, 3], 
     ...:  [186, 302, 3], 
     ...:  [22, 377, 1],
     ...:  [196, 377, 3]]

从中生成一个数组-以便于执行以下操作

In [169]: A = np.array(ll)
In [170]: ll
Out[170]: [[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3]]
In [171]: A
Out[171]: 
array([[196, 242,   3],
       [186, 302,   3],
       [ 22, 377,   1],
       [196, 377,   3]])

将索引列移到0基(可选)

In [172]: A[:,:2] -= 1

使用这种方法,可以使用coo(或csr)格式,即(data, (rows, cols)),快速而简单地定义稀疏矩阵。迭代dok方法是可行的,但速度更快。你知道吗

In [174]: from scipy import sparse
In [175]: M = sparse.csr_matrix((A[:,2],(A[:,0], A[:,1])), shape=(942,1681))
In [176]: M
Out[176]: 
<942x1681 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Compressed Sparse Row format>
In [177]: print(M)
  (21, 376) 1
  (185, 301)    3
  (195, 241)    3
  (195, 376)    3

M.A从这个稀疏矩阵创建一个密集数组。一些代码,尤其是sckit-learn包中的代码可以直接使用稀疏矩阵。你知道吗

创建密集阵列的直接方法是:

In [183]: N = np.zeros((942,1681),int)
In [184]: N[A[:,0],A[:,1]]= A[:,2]
In [185]: N.shape
Out[185]: (942, 1681)
In [186]: M.A.shape
Out[186]: (942, 1681)
In [187]: np.allclose(N, M.A)   # it matches the sparse version
Out[187]: True

相关问题 更多 >