当我们想要计算矩阵的稀疏性时,.nonzero()[0] 是什么意思?

What does .nonzero()[0] mean when we want to compute the sparsity of a matrix?

我正在尝试通过阅读博客了解 Python 中的推荐系统,该博客包含在 GitHub 中创建存储库推荐系统的一个很好的例子。

使用 read_csv() 加载数据集后,编写代码的人决定将该数据转换为 pivot_table pandas 以便以更简单的方式可视化数据方法。在这里,为了简单起见,我给你留下了那部分代码的图像:

enter image description here

在 table 中,行是用户,列是存储库。行和列之间的横截面是用户给特定存储库的标点符号。

由于 table 的许多元素都是空的(我们可以说我们有一个稀疏矩阵,在机器学习中非常典型),他决定研究稀疏度通过此代码的矩阵:

ratings = df_matrix.values
sparsity = float(len(ratings.nonzero()[0]))
sparsity /= (ratings.shape[0] * ratings.shape[1])
sparsity *= 100
print('Sparsity: {:4.2f}%'.format(sparsity))

谁能帮我知道第二行代码是什么意思? 我想我明白 ratings.nonzero() returns 一个列表,其中包含所有不为零的元素的索引,并且由于我对总数而不是索引感兴趣,因此有必要使用len(ratings.nonzero()),但我的问题是我不可能知道 [0] 在代码中的含义。

非常感谢,对于给您带来的不便,我们深表歉意!

默认情况下,nonzero 将 return 形式为 (row_idxs, col_idxs) 的元组。如果你给它一个一维数组(比如 pandas 系列),那么它仍然会 return 一个元组,(row_idxs,)。要访问第一个数组,我们仍然必须索引 ratings.nonzero()[0] 以获得非零元素的第一维索引。

nonzero here 的 numpy 页面上提供了更多信息,因为 pandas 和 numpy 使用相同的实现。