how can i display sparsity of data where: #Filter Sparse Data
user_counts = ratings['User-ID'].value_counts()
ratings = ratings[ratings['User-ID'].isin(user_counts[user_counts >= 5].index)]
Show how ratings are distributed across users and books:
python
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
# Ratings per user distribution
user_rating_counts = ratings.groupby('User-ID').size()
ax1.hist(user_rating_counts, bins=50, edgecolor='black')
ax1.set_xlabel('Number of Ratings')
ax1.set_ylabel('Number of Users')
ax1.set_title('Distribution of Ratings per User')
ax1.axvline(user_rating_counts.mean(), color='red', linestyle='--', label=f'Mean: {user_rating_counts.mean():.1f}')
ax1.legend()
# Ratings per book distribution
book_rating_counts = ratings.groupby('ISBN').size()
ax2.hist(book_rating_counts, bins=50, edgecolor='black')
ax2.set_xlabel('Number of Ratings')
ax2.set_ylabel('Number of Books')
ax2.set_title('Distribution of Ratings per Book')
ax2.axvline(book_rating_counts.mean(), color='red', linestyle='--', label=f'Mean: {book_rating_counts.mean():.1f}')
ax2.legend()
plt.tight_layout()
plt.show()
4. Cumulative Distribution
Show what percentage of users/books account for what percentage of ratings:
python
# Calculate cumulative distributions
user_rating_counts_sorted = user_rating_counts.sort_values(ascending=False)
book_rating_counts_sorted = book_rating_counts.sort_values(ascending=False)
user_cumsum = user_rating_counts_sorted.cumsum() / total_ratings
book_cumsum = book_rating_counts_sorted.cumsum() / total_ratings
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(np.arange(1, len(user_cumsum)+1) / len(user_cumsum) * 100, user_cumsum * 100)
plt.xlabel('Percentage of Users')
plt.ylabel('Percentage of Total Ratings')
plt.title('Cumulative Distribution of Ratings by Users')
plt.grid(True, alpha=0.3)
plt.subplot(1, 2, 2)
plt.plot(np.arange(1, len(book_cumsum)+1) / len(book_cumsum) * 100, book_cumsum * 100)
plt.xlabel('Percentage of Books')
plt.ylabel('Percentage of Total Ratings')
plt.title('Cumulative Distribution of Ratings by Books')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
5. Before/After Filtering Comparison
Show the impact of your filtering:
python
# Assuming you have the original data saved
original_sparsity = 1 - (len(original_ratings) / (original_ratings['User-ID'].nunique() * original_ratings['ISBN'].nunique()))
filtered_sparsity = sparsity
data = {
'Metric': ['Users', 'Books', 'Ratings', 'Sparsity'],
'Before Filtering': [
original_ratings['User-ID'].nunique(),
original_ratings['ISBN'].nunique(),
len(original_ratings),
f"{original_sparsity:.2%}"
],
'After Filtering': [
total_users,
total_books,
total_ratings,
f"{filtered_sparsity:.2%}"
]
}
comparison_df = pd.DataFrame(data)
print(comparison_df.to_string(index=False))
These visualizations will help you understand the sparsity patterns in your data and communicate them effectively. The heatmap gives a visual representation, the statistics provide concrete numbers, and the distribution plots show how ratings are spread across users and books.
User
how can i check in my notebook
Assistant
Here's a simple way to check the sparsity of your data directly in your notebook:
python
# Quick sparsity check
def check_sparsity(ratings_df):
# Basic statistics
n_users = ratings_df['User-ID'].nunique()
n_books = ratings_df['ISBN'].nunique()
n_ratings = len(ratings_df)
# Calculate sparsity
total_possible = n_users * n_books
sparsity = 1 - (n_ratings / total_possible)
# Display results
print("=== Data Sparsity Analysis ===")
print(f"Number of users: {n_users:,}")
print(f"Number of books: {n_books:,}")
print(f"Number of ratings: {n_ratings:,}")
print(f"Total possible ratings: {total_possible:,}")
print(f"\nSparsity: {sparsity:.4%}")
print(f"Density: {(1-sparsity):.4%}")
# Average ratings per user and book
avg_ratings_per_user = n_ratings / n_users
avg_ratings_per_book = n_ratings / n_books
print(f"\nAverage ratings per user: {avg_ratings_per_user:.2f}")
print(f"Average ratings per book: {avg_ratings_per_book:.2f}")
return sparsity
# Run the check
sparsity = check_sparsity(ratings)
For a quick visual check, you can also create a simple bar chart:
python
# Visual sparsity representation
import matplotlib.pyplot as plt
# Create a simple visualization
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
# Show filled vs empty cells
filled = len(ratings)
total = ratings['User-ID'].nunique() * ratings['ISBN'].nunique()
empty = total - filled
ax.bar(['Filled (Ratings)', 'Empty (No Ratings)'], [filled, empty],
color=['#2ecc71', '#e74c3c'])
ax.set_ylabel('Number of Cells')
ax.set_title(f'Rating Matrix Sparsity: {sparsity:.2%} sparse')
# Add percentage labels
for i, (label, value) in enumerate(zip(['Filled', 'Empty'], [filled, empty])):
percentage = value / total * 100
ax.text(i, value + total*0.01, f'{percentage:.2f}%', ha='center')
plt.tight_layout()
plt.show()
These methods will quickly show you how sparse your filtered data is. The first function gives you comprehensive statistics, while the visualization helps you see the proportion of filled vs empty cells in your user-item matrix.