开始使用免费开始使用

计算稀疏度

您已经知道,ALS 适合处理稀疏数据集。我们来看看 ratings 矩阵中有多少实际上是空的。

请记住,稀疏度的计算方式是:矩阵中实际包含评分的单元格数量,除以在给定用户数和物品数(电影)条件下矩阵可能容纳的总单元格数量。也就是说,用矩阵中已有评分的数量除以矩阵中的用户数与电影数的乘积,再用 1 减去该比值,就得到稀疏度,即 ratings 矩阵中为空的比例。

本练习是课程的一部分

使用 PySpark 构建推荐引擎

查看课程

练习说明

  • 通过统计 ratings 矩阵中评分的总数量,计算稀疏度指标的 numerator(分子)。
  • 统计 ratings 矩阵中 distinct()userIdsdistinct()movieIds 数量。
  • 将用户数与电影数相乘,计算稀疏度指标的 denominator(分母)。
  • 计算并打印稀疏度:用 numerator 除以 denominator,再用 1 减去该结果并乘以 100。加入 1.0 是为了确保稀疏度以小数而不是整数返回。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Count the total number of ratings in the dataset
numerator = ____.select("____").count()

# Count the number of distinct userIds and distinct movieIds
num_users = ____.select("____").____().count()
num_movies = ____.select("____").____().count()

# Set the denominator equal to the number of users multiplied by the number of movies
denominator = ____ * ____

# Divide the numerator by the denominator
sparsity = (1.0 - (____ *1.0)/____)*100
print("The ratings dataframe is ", "%.2f" % sparsity + "% empty.")
编辑并运行代码