Problems
Loading...
1 / 1

Mean Rating Imputation

Recommender SystemsData Processing
Medium

Rating matrices in recommender systems are extremely sparse (often 95-99% missing). Many algorithms require a dense matrix, so missing values must be filled in (imputed). Mean imputation is the simplest approach: replace each missing rating with the mean of known ratings, either along the user dimension (user mean) or the item dimension (item mean).

Given a ratings matrix (users x items, 0 = missing) and a mode ("user" or "item"), fill in all missing values with the appropriate mean.

Strategy

In "user" mode, each missing entry is filled with the mean of that user's non-zero ratings. In "item" mode, each missing entry is filled with the mean of that item's non-zero ratings across all users.

Loading visualization...

Examples

Input:

ratings = [[5,3,0],[4,0,2],[0,1,5]], mode = "user"

Output:

[[5, 3, 4.0], [4, 3.0, 2], [3.0, 1, 5]]

User 0 mean = (5+3)/2 = 4.0, fills position [0][2]. User 1 mean = (4+2)/2 = 3.0, fills [1][1]. User 2 mean = (1+5)/2 = 3.0, fills [2][0].

Input:

ratings = [[5,3,0],[4,0,2],[0,1,5]], mode = "item"

Output:

[[5, 3, 3.5], [4, 2.0, 2], [4.5, 1, 5]]

Item 0 mean = (5+4)/2 = 4.5, fills [2][0]. Item 1 mean = (3+1)/2 = 2.0, fills [1][1]. Item 2 mean = (2+5)/2 = 3.5, fills [0][2].

Hint 1

For user mode, iterate over each row. Compute the mean of non-zero entries in that row. Then replace all zeros in that row with the computed mean.

Hint 2

For item mode, iterate over each column index. Collect non-zero entries from all rows at that column position. Compute the mean, then fill zeros in that column.

Requirements

  • Treat 0 as missing (unrated), not as a valid rating
  • In "user" mode, fill missing entries with the mean of that user's non-zero ratings
  • In "item" mode, fill missing entries with the mean of that item's non-zero ratings
  • Return a new matrix without modifying the input

Constraints

  • ratings_matrix is a list of lists, 0 means missing
  • mode is either "user" or "item"
  • Return a new list of lists with the same dimensions
  • Time limit: 300 ms
Try Similar Problems