희소성 계산하기
아시다시피 ALS는 희소한 데이터셋에서 잘 작동해요. ratings 행렬에서 실제로 얼마나 많은 부분이 비어 있는지 확인해 보겠습니다.
희소성(sparsity)은 사용자와 아이템(영화) 수가 주어졌을 때, 해당 행렬이 가질 수 있는 전체 값의 개수 중에서 실제 평점이 들어 있는 셀의 비율로 계산합니다. 다시 말해, 행렬에 존재하는 평점의 개수를 사용자 수와 영화 수의 곱으로 나눈 값을 1에서 빼면, ratings 행렬에서 비어 있는 셀의 비율, 즉 희소성을 얻을 수 있어요.
이 연습은 강의의 일부입니다
PySpark로 추천 엔진 만들기
연습 안내
ratings행렬에 포함된 전체 평점 수를 세어 희소성 지표의numerator를 계산하세요.ratings행렬에서distinct()userIds와distinct()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.")