Surya_from_1627

USML9

Sep 28th, 2026
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. import numpy as np
  2. from sklearn.decomposition import TruncatedSVD
  3.  
  4. def estimate_ratings_svd(rating_matrix, n_components=5):
  5.     """
  6.    Estimates missing ratings in a user-item rating matrix using Truncated SVD.
  7.  
  8.    Args:
  9.        rating_matrix (np.array): A 2D NumPy array representing the user-item
  10.                                  rating matrix. Missing ratings should be
  11.                                  represented by NaN or 0 (if 0 is not a valid rating).
  12.        n_components (int): The number of latent features to use for SVD.
  13.  
  14.    Returns:
  15.        np.array: A reconstructed rating matrix with estimated ratings for
  16.                  missing values.
  17.    """
  18.     # Create a copy to avoid modifying the original matrix
  19.     matrix_filled = np.nan_to_num(rating_matrix, nan=0) # Replace NaN with 0 for SVD
  20.  
  21.     # Perform Truncated SVD
  22.     svd = TruncatedSVD(n_components=n_components)
  23.     U = svd.fit_transform(matrix_filled)
  24.     Sigma = np.diag(svd.singular_values_)
  25.     Vt = svd.components_
  26.  
  27.     # Reconstruct the matrix
  28.     # Note: For full reconstruction, we would use U @ Sigma @ Vt.
  29.     # However, for rating prediction, we often use the reduced dimensions directly.
  30.     # Here, we're effectively reconstructing the matrix based on the k-latent factors.
  31.     reconstructed_matrix = U @ Sigma @ Vt
  32.  
  33.     # Only fill in the values that were originally missing
  34.     estimated_matrix = np.copy(rating_matrix)
  35.     missing_indices = np.isnan(rating_matrix)
  36.     estimated_matrix[missing_indices] = reconstructed_matrix[missing_indices]
  37.  
  38.     return estimated_matrix
  39.  
  40. # Example Usage:
  41. if __name__ == "__main__":
  42.     # Sample user-item rating matrix (NaN represents missing ratings)
  43.     # Rows are users, columns are items
  44.     ratings = np.array([
  45.         [5, 3, np.nan, 1, 4],
  46.         [4, np.nan, 5, 2, np.nan],
  47.         [1, 2, 3, np.nan, 5],
  48.         [np.nan, 4, 1, 5, 2]
  49.     ])
  50.  
  51.     print("Original Rating Matrix:")
  52.     print(ratings)
  53.  
  54.     # Estimate missing ratings using SVD with 3 latent components
  55.     estimated_ratings = estimate_ratings_svd(ratings, n_components=3)
  56.  
  57.     print("\nEstimated Rating Matrix:")
  58.     print(estimated_ratings)
Advertisement
Add Comment
Please, Sign In to add comment