Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from sklearn.decomposition import TruncatedSVD
- def estimate_ratings_svd(rating_matrix, n_components=5):
- """
- Estimates missing ratings in a user-item rating matrix using Truncated SVD.
- Args:
- rating_matrix (np.array): A 2D NumPy array representing the user-item
- rating matrix. Missing ratings should be
- represented by NaN or 0 (if 0 is not a valid rating).
- n_components (int): The number of latent features to use for SVD.
- Returns:
- np.array: A reconstructed rating matrix with estimated ratings for
- missing values.
- """
- # Create a copy to avoid modifying the original matrix
- matrix_filled = np.nan_to_num(rating_matrix, nan=0) # Replace NaN with 0 for SVD
- # Perform Truncated SVD
- svd = TruncatedSVD(n_components=n_components)
- U = svd.fit_transform(matrix_filled)
- Sigma = np.diag(svd.singular_values_)
- Vt = svd.components_
- # Reconstruct the matrix
- # Note: For full reconstruction, we would use U @ Sigma @ Vt.
- # However, for rating prediction, we often use the reduced dimensions directly.
- # Here, we're effectively reconstructing the matrix based on the k-latent factors.
- reconstructed_matrix = U @ Sigma @ Vt
- # Only fill in the values that were originally missing
- estimated_matrix = np.copy(rating_matrix)
- missing_indices = np.isnan(rating_matrix)
- estimated_matrix[missing_indices] = reconstructed_matrix[missing_indices]
- return estimated_matrix
- # Example Usage:
- if __name__ == "__main__":
- # Sample user-item rating matrix (NaN represents missing ratings)
- # Rows are users, columns are items
- ratings = np.array([
- [5, 3, np.nan, 1, 4],
- [4, np.nan, 5, 2, np.nan],
- [1, 2, 3, np.nan, 5],
- [np.nan, 4, 1, 5, 2]
- ])
- print("Original Rating Matrix:")
- print(ratings)
- # Estimate missing ratings using SVD with 3 latent components
- estimated_ratings = estimate_ratings_svd(ratings, n_components=3)
- print("\nEstimated Rating Matrix:")
- print(estimated_ratings)
Advertisement
Add Comment
Please, Sign In to add comment