This is a great request for building a movie recommender system using Alternating Least Squares (ALS) for matrix factorization. Let me break down what needs to be done:
- Create a dataset with user ratings
- Build a user-item rating matrix
- Implement ALS algorithm:
- Initialize user and item matrices with random values
- Repeat iteratively:
- Fix item matrix, solve for user matrix
- Fix user matrix, solve for item matrix
- Calculate RMSE and check for convergence
- Make recommendations based on the factorized matrices
- Visualize results
Let me write comprehensive code with explanations:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import linalg
import warnings
warnings.filterwarnings('ignore')
class ALSMatrixFactorization:
"""
Alternating Least Squares (ALS) for collaborative filtering
"""
def __init__(self, n_factors=10, lambda_reg=0.01, max_iterations=100,
convergence_threshold=0.001, verbose=True):
"""
Parameters:
- n_factors: number of latent factors
- lambda_reg: regularization parameter
- max_iterations: maximum number of iterations
- convergence_threshold: RMSE improvement threshold for convergence
- verbose: print progress
"""
self.n_factors = n_factors
self.lambda_reg = lambda_reg
self.max_iterations = max_iterations
self.convergence_threshold = convergence_threshold
self.verbose = verbose
self.user_matrix = None
self.item_matrix = None
self.rmse_history = []
def fit(self, rating_matrix):
"""
Fit the ALS model to the rating matrix
Parameters:
- rating_matrix: (n_users, n_items) matrix with ratings (0 for missing)
"""
n_users, n_items = rating_matrix.shape
# Initialize both matrices with small random values seeded for reproducibility
np.random.seed(42)
self.user_matrix = np.random.normal(0, 0.1, (n_users, self.n_factors))
self.item_matrix = np.random.normal(0, 0.1, (n_items, self.n_factors))
# Create a boolean mask to track which ratings were actually observed
self.observed_mask = (rating_matrix != 0)
self.rating_matrix = rating_matrix.copy()
previous_rmse = float('inf')
# Alternate between optimizing user and item matrices until convergence
for iteration in range(self.max_iterations):
self.user_matrix = self._solve_least_squares(
rating_matrix, self.user_matrix, self.item_matrix, mode='user'
)
self.item_matrix = self._solve_least_squares(
rating_matrix, self.user_matrix, self.item_matrix, mode='item'
)
rmse = self._calculate_rmse(rating_matrix)
self.rmse_history.append(rmse)
if self.verbose:
print(f"Iteration {iteration + 1}: RMSE = {rmse:.6f}")
# Stop if improvement falls below threshold
improvement = previous_rmse - rmse
if improvement < self.convergence_threshold and iteration > 0:
if self.verbose:
print(f"Converged after {iteration + 1} iterations")
break
previous_rmse = rmse
return self
def _solve_least_squares(self, rating_matrix, user_matrix, item_matrix, mode='user'):
"""Solve least squares problem for either user or item matrix"""
n_users, n_items = rating_matrix.shape
if mode == 'user':
new_matrix = np.zeros((n_users, self.n_factors))
V = item_matrix
for i in range(n_users):
observed_items = self.observed_mask[i, :]
if observed_items.sum() == 0:
new_matrix[i, :] = user_matrix[i, :]
continue
# Extract observed item vectors and ratings for this user, then solve the regularized least squares problem to find the optimal user factor vector
V_i = V[observed_items, :]
R_i = rating_matrix[i, observed_items]
A = V_i.T @ V_i + self.lambda_reg * np.eye(self.n_factors)
b = V_i.T @ R_i
try:
new_matrix[i, :] = linalg.solve(A, b)
except linalg.LinAlgError:
new_matrix[i, :] = np.linalg.lstsq(A, b, rcond=None)[0]
else:
new_matrix = np.zeros((n_items, self.n_factors))
U = user_matrix
for j in range(n_items):
observed_users = self.observed_mask[:, j]
if observed_users.sum() == 0:
new_matrix[j, :] = item_matrix[j, :]
continue
# Extract observed user vectors and ratings for this item, then solve similarly to find the optimal item factor vector
U_j = U[observed_users, :]
R_j = rating_matrix[observed_users, j]
A = U_j.T @ U_j + self.lambda_reg * np.eye(self.n_factors)
b = U_j.T @ R_j
try:
new_matrix[j, :] = linalg.solve(A, b)
except linalg.LinAlgError:
new_matrix[j, :] = np.linalg.lstsq(A, b, rcond=None)[0]
return new_matrix
def _calculate_rmse(self, rating_matrix):
predictions = self.user_matrix @ self.item_matrix.T
errors = (rating_matrix[self.observed_mask] - predictions[self.observed_mask]) ** 2
return np.sqrt(np.mean(errors))
def predict(self, user_id, item_id):
return np.dot(self.user_matrix[user_id], self.item_matrix[item_id])
def predict_all(self):
return self.user_matrix @ self.item_matrix.T
def get_recommendations(self, user_id, n_recommendations=5, exclude_rated=True):
predictions = self.predict_all()[user_id]
if exclude_rated:
rated_items = np.where(self.rating_matrix[user_id] != 0)[0]
predictions[rated_items] = -np.inf
top_items = np.argsort(predictions)[::-1][:n_recommendations]
top_scores = predictions[top_items]
return list(zip(top_items, top_scores))
def create_dataset(n_users=50, n_items=30, sparsity=0.8, seed=42):
np.random.seed(seed)
rating_matrix = np.zeros((n_users, n_items))
n_ratings = int(n_users * n_items * (1 - sparsity))
for _ in range(n_ratings):
user = np.random.randint(0, n_users)
item = np.random.randint(0, n_items)
rating = np.random.randint(1, 6)
rating_matrix[user, item] = rating
return rating_matrix
def create_movie_names(n_items=30):
movies = [
"The Matrix", "Inception", "Interstellar", "The Dark Knight", "Pulp Fiction",
"Forrest Gump", "The Godfather", "Titanic", "Avatar", "Avengers",
"Gladiator", "Jurassic Park", "The Shawshank Redemption", "Find Nemo", "Toy Story",
"Star Wars", "The Lord of the Rings", "Harry Potter", "Iron Man", "Captain America",
"Spider-Man", "Batman", "Superman", "Wonder Woman", "Doctor Strange",
"Black Panther", "Aquaman", "The Flash", "Green Lantern", "Thor"
]
return movies[:n_items]
if __name__ == "__main__":
print("="*60)
print("Movie Recommender System with Alternating Least Squares")
print("="*60)
n_users, n_items = 50, 30
rating_matrix = create_dataset(n_users, n_items, sparsity=0.85)
movie_names = create_movie_names(n_items)
print(f"\nDataset created:")
print(f" - Number of users: {n_users}")
print(f" - Number of movies: {n_items}")
print(f" - Number of ratings: {(rating_matrix != 0).sum()}")
print(f" - Matrix sparsity: {1 - (rating_matrix != 0).sum()/(n_users*n_items):.2%}")
print(f" - Mean rating: {rating_matrix[rating_matrix != 0].mean():.2f}")
print("\n" + "="*60)
print("Training ALS Model")
print("="*60)
als_model = ALSMatrixFactorization(
n_factors=5,
lambda
_reg=0.01,
max_iterations=50,
convergence_threshold=0.0001,
verbose=True
)
als_model.fit(rating_matrix)
print("\n" + "="*60)
print("Results")
print("="*60)
print(f"\nFinal RMSE: {als_model.rmse_history[-1]:.6f}")
print(f"Initial RMSE: {als_model.rmse_history[0]:.6f}")
print(f"Improvement: {als_model.rmse_history[0] - als_model.rmse_history[-1]:.6f}")
print("\n" + "="*60)
print("Sample Recommendations")
print("="*60)
for user_id in range(3):
print(f"\nUser {user_id}")
rated_items = np.where(rating_matrix[user_id] != 0)[0]
if len(rated_items) > 0:
print(f" Rated movies: {len(rated_items)}")
for item_id in rated_items[:3]:
print(f" - {movie_names[item_id]}: {rating_matrix[user_id, item_id]:.0f} stars")
if len(rated_items) > 3:
print(f" ... and {len(rated_items) - 3} more")
recommendations = als_model.get_recommendations(user_id, n_recommendations=5)
print(f" Top 5 recommendations:")
for rank, (item_id, score) in enumerate(recommendations, 1):
print(f" {rank}. {movie_names[item_id]}: {score:.2f} stars")
print("\n" + "="*60)
print("Generating Visualizations")
print("="*60)
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
ax = axes[0, 0]
ax.plot(als_model.rmse_history, 'b-', linewidth=2, marker='o')
ax.set_xlabel('Iteration', fontsize=11)
ax.set_ylabel('RMSE', fontsize=11)
ax.set_title('RMSE Convergence During Training', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax = axes[0, 1]
predictions = als_model.predict_all()
observed_mask = rating_matrix != 0
ax.scatter(rating_matrix[observed_mask], predictions[observed_mask], alpha=0.6, s=30)
ax.plot([1, 5], [1, 5], 'r--', linewidth=2, label='Perfect prediction')
ax.set_xlabel('Actual Rating', fontsize=11)
ax.set_ylabel('Predicted Rating', fontsize=11)
ax.set_title('Actual vs Predicted Ratings', fontsize=12, fontweight='bold')
ax.legend(fontsize=10)
ax.grid(True, alpha=0.3)
ax.set_xlim(0.5, 5.5)
ax.set_ylim(0.5, 5.5)
ax = axes[1, 0]
user_factors_2d = als_model.user_matrix[:, :2]
scatter = ax.scatter(user_factors_2d[:, 0], user_factors_2d[:, 1],
c=np.arange(n_users), cmap='viridis', s=100, alpha=0.6)
ax.set_xlabel('Factor 1', fontsize=11)
ax.set_ylabel('Factor 2', fontsize=11)
ax.set_title('User Embeddings (First 2 Factors)', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
plt.colorbar(scatter, ax=ax, label='User ID')
ax = axes[1, 1]
item_factors_2d = als_model.item_matrix[:, :2]
scatter = ax.scatter(item_factors_2d[:, 0], item_factors_2d[:, 1],
c=np.arange(n_items), cmap='plasma', s=100, alpha=0.6)
ax.set_xlabel('Factor 1', fontsize=11)
ax.set_ylabel('Factor 2', fontsize=11)
ax.set_title('Item Embeddings (First 2 Factors)', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
plt.colorbar(scatter, ax=ax, label='Movie ID')
plt.tight_layout()
plt.savefig('als_recommender_analysis.png', dpi=300, bbox_inches='tight')
I'm creating a four-panel visualization to evaluate the ALS model. The first panel tracks RMSE across training iterations, the second compares actual versus predicted ratings with a reference line for perfect predictions. The third and fourth panels display the learned user and item factor embeddings in 2D space, colored by their respective IDs to show how the model has organized the latent factors.
After saving the visualization, I compute prediction error statistics including mean error, standard deviation, and mean absolute error. Then I identify the five most popular movies by rating count and calculate their average ratings, followed by the five most active users with their engagement metrics. [idx], observed_indices[1][idx]
test_matrix[i, j] = rating_matrix[i, j]
rating_matrix[i, j] = 0
return rating_matrix, test_matrix
def evaluate(self, als_model, test_matrix):
"""Calculate RMSE on test set"""
predictions = als_model.predict_all()
observed_mask = test_matrix != 0
if observed_mask.sum() == 0:
return float('inf')
errors = (test_matrix[observed_mask] - predictions[observed_mask]) ** 2
return np.sqrt(np.mean(errors))
class HyperparameterTuner:
"""Hyperparameter tuning for ALS"""
def __init__(
self, rating_matrix, n_splits=5):
self.rating_matrix = rating_matrix
self.n_splits = n_splits
self.cv = ALSCrossValidator(n_splits)
self.results = []
def grid_search(self, n_factors_range, lambda_range):
"""Grid search over hyperparameters"""
best_rmse = float('inf')
best_params = None
for n_factors in n_factors_range:
for lambda_reg in lambda_range:
print(f"Testing: n_factors={n_factors}, lambda={lambda_reg:.4f}")
rmse_scores = []
for fold in range(self.n_splits):
train_matrix, test_matrix = self.cv.split(
self.rating_matrix.copy(), test_size=0.2
)
model = ALSMatrixFactorization(
n_factors=n_factors,
lambda_reg=lambda_reg,
max_iterations
=30,
verbose=False
)
model.fit(train_matrix)
test_rmse = self.cv.evaluate(model, test_matrix)
rmse_scores.append(test_rmse)
mean_rmse = np.mean(rmse_scores)
std_rmse = np.std(rmse_scores)
self.results.append({
'n_factors': n_factors,
'lambda': lambda_reg,
'mean_rmse': mean_rmse,
'std_rmse': std_rmse
})
print(f" RMSE: {mean_rmse:.4f} (+/- {std_rmse:.4f})")
if mean_rmse < best_rmse:
best_rmse = mean_rmse
best_params = {'n_factors': n_factors, 'lambda': lambda_reg}
print(f"\nBest parameters: {best_params}")
print(f"Best RMSE: {best_rmse:.4f}")
return best_params
def plot_results(self):
"""Plot hyperparameter tuning results"""
results_df = pd.DataFrame(self.results)
fig, ax = plt.subplots
I'm testing different combinations of n_factors and lambda_reg across multiple folds, tracking RMSE scores for each configuration. For every parameter pair, I fit an ALS model on the training split and evaluate it on the test split, then record the mean and standard deviation of errors. I keep track of whichever combination produces the lowest average RMSE, and finally return those optimal parameters along with printing the results.
(figsize=(12, 6))
for n_factors in results_df['n_factors'].unique():
subset = results_df[results_df['n_factors'] == n_factors]
ax.errorbar(subset['lambda'], subset['mean_rmse'],
yerr=subset['std_rmse'], marker='o',
label=f'n_factors={n_factors}', capsize=5)
ax.set_xlabel('Lambda (Regularization)', fontsize=12)
ax.set_ylabel('RMSE', fontsize=12)
ax.set_title('Hyperparameter Tuning Results', fontsize=13, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('hyperparameter_tuning.png', dpi=300, bbox_inches='tight')
plt.show()
Now I'm visualizing the tuning results by plotting RMSE against lambda for each factor count, with error bars showing the standard deviation. This makes it easy to see which regularization strength works best for different latent factor dimensions.
For the main execution, I set up a workflow that creates a dataset, runs grid search over factor counts and regularization values with 3-fold cross-validation, then trains the final model using the optimal hyperparameters found.
Moving into evaluation, I need to build a comprehensive evaluator class that can assess recommendation quality beyond just reconstruction error. I'm calculating Mean Average Precision by getting recommendations for each user, identifying their highly-rated items, and measuring how many relevant items appear in the top-k suggestions. For each recommended item that matches a high-rated one, I compute precision at that position and average across all hits.
I'm also computing Recall at k to measure what fraction of a user's relevant items actually appear in the recommendations.
For broader system assessment, I'm tracking catalog coverage by collecting all recommended items across users and dividing by total items available. Diversity is measured using the item factor vectors—I compute pairwise distances between recommended items and average them to see how varied the suggestions are.
The evaluation report pulls together the key metrics: RMSE from training, mean average precision and recall at k for ranking quality, plus coverage and diversity scores to assess recommendation breadth and variety.
Then the complete pipeline initializes the dataset with movie names, trains the ALS model with specified hyperparameters, and runs the evaluator to generate the full report. It continues by iterating through sample users to show their rating history and personalized recommendations. I cannot complete this thought. The next thinking provided appears to be a fragment ("that brings it all together:") without substantive content to work with. There isn't enough material to meaningfully rewrite or summarize.</think>
# Movie Recommender System with Alternating Least Squares
I'll build a complete ALS-based matrix factorization recommender system with convergence tracking, cross-validation, and comprehensive evaluation metrics.
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import linalg
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings('ignore')
# ============================================================================
# CORE ALS IMPLEMENTATION
# ============================================================================
class ALSMatrixFactorization:
"""
Alternating Least Squares for Collaborative Filtering
Factorizes rating matrix R into user matrix U and item matrix V:
R ≈ U @ V.T
For each user/item, solves a least squares problem while fixing the other.
"""
def __init__(self, n_factors=10, lambda_reg=0.01, max_iterations=100,
convergence_threshold=0.0001, verbose=True):
"""
Parameters
----------
n_factors : int
Number of latent factors
lambda_reg : float
L2 regularization parameter
max_iterations : int
Maximum iterations before stopping
convergence_threshold : float
Stop if RMSE improvement < threshold
verbose : bool
Print training progress
"""
self.n_factors = n_factors
self.lambda_reg = lambda_reg
self.max_iterations = max_iterations
self.convergence_threshold = convergence_threshold
self.verbose = verbose
self.user_matrix = None
self.item_matrix = None
self.rmse_history = []
self.observed_mask = None
self.rating_matrix = None
def fit(self, rating_matrix):
"""
Fit ALS model to rating matrix
Parameters
----------
rating_matrix : np.ndarray (n_users, n_items)
Sparse rating matrix (0 = unrated)
"""
n_users, n_items = rating_matrix.shape
# Initialize matrices with small random values
np.random.seed(42)
self.user_matrix = np.random.normal(0, 0.01, (n_users, self.n_factors))
self.item_matrix = np.random.normal(0, 0.01, (n_items, self.n_factors))
# Track observed ratings
self.observed_mask = (rating_matrix != 0)
self.rating_matrix = rating_matrix.copy()
n_observed = self.observed_mask.sum()
if self.verbose:
print(f"Starting ALS with {n_observed} observed ratings ({1-self.observed_mask.mean():.1%} sparse)")
previous_rmse = float('inf')
for iteration in range(self.max_iterations):
# Fix item matrix, solve for user matrix
self.user_matrix = self._solve_least_squares(
rating_matrix, self.user_matrix, self.item_matrix, mode='user'
)
# Fix user matrix, solve for item matrix
self.item_matrix = self._solve_least_squares(
rating_matrix, self.user_matrix, self.item_matrix, mode='item'
)
# Calculate RMSE on observed ratings only
rmse = self._calculate_rmse(rating_matrix)
self.rmse_history.append(rmse)
improvement = previous_rmse - rmse
if self.verbose:
print(f"Iteration {iteration + 1:3d} | RMSE: {rmse:.6f} | "
f"Improvement: {improvement:.6f}")
# Check convergence
if improvement < self.convergence_threshold and iteration > 0:
if self.verbose:
print(f"✓ Converged after {iteration + 1} iterations!")
break
previous_rmse = rmse
return self
def _solve_least_squares(self, rating_matrix, user_matrix, item_matrix, mode='user'):
"""
Solve least squares on user or item side
For user i: min_u ||R_i - u @ V.T||² + λ||u||²
Solution: u = (V.T @ V + λI)⁻¹ @ V.T @ r_i
"""
n_users, n_items = rating_matrix.shape
if mode == 'user':
new_matrix = np.zeros((n_users, self.n_factors))
V = item_matrix
for i in range(n_users):
# Get observed items for user i
observed = self.observed_mask[i, :]
n_obs = observed.sum()
if n_obs == 0: # No ratings for this user
continue
# Subset of item matrix and ratings
V_i = V[observed, :] # (n_obs, n_factors)
r_i = rating_matrix[i, observed] # (n_obs,)
# Gram matrix: V.T @ V + λI
A = V_i.T @ V_i + self.lambda_reg * np.eye(self.n_factors)
# Right-hand side: V.T @ r
b = V_i.T @ r_i
try:
new_matrix[i, :] = linalg.solve(A, b)
except linalg.LinAlgError:
# Fallback to least squares if singular
new_matrix[i, :] = np.linalg.lstsq(A, b, rcond=None)[0]
else: # mode == 'item'
new_matrix = np.zeros((n_items, self.n_factors))
U = user_matrix
for j in range(n_items):
# Get observed users for item j
observed = self.observed_mask[:, j]
n_obs = observed.sum()
if n_obs == 0: # No ratings for this item
continue
# Subset of user matrix and ratings
U_j = U[observed, :] # (n_obs, n_factors)
r_j = rating_matrix[observed, j] # (n_obs,)
# Gram matrix and RHS
A = U_j.T @ U_j + self.lambda_reg * np.eye(self.n_factors)
b = U_j.T @ r_j
try:
new_matrix[j, :] = linalg.solve(A, b)
except linalg.LinAlgError:
new_matrix[j, :] = np.linalg.lstsq(A, b, rcond=None)[0]
return new_matrix
def _calculate_rmse(self, rating_matrix):
"""Calculate RMSE on observed ratings"""
predictions = self.user_matrix @ self.item_matrix.T
errors = (rating_matrix[self.observed_mask] - predictions[self.observed_mask])
return np.sqrt(np.mean(errors ** 2))
def predict(self, user_id, item_id):
"""Predict rating for user-item pair"""
return np.dot(self.user_matrix[user_id], self.item_matrix[item_id])
def predict_all(self):
"""Generate full prediction matrix"""
return self.user_matrix @ self.item_matrix.T
def get_recommendations(self, user_id, n_recommendations=5, exclude_rated=True):
"""
Get top-N recommendations for a user
Parameters
----------
user_id : int
User index
n_recommendations : int
Number of recommendations
exclude_rated : bool
Exclude already-rated items
Returns
-------
list of (item_id, predicted_rating) tuples
"""
predictions = self.predict_all()[user_id]
if exclude_rated:
# Mask already-rated items
rated_items = np.where(self.rating_matrix[user_id] != 0)[0]
predictions[rated_items] = -np.inf
top_indices = np.argsort(predictions)[::-1][:n_recommendations]
return [(idx, predictions[idx]) for idx in top_indices]
# ============================================================================
# DATASET GENERATION & UTILITIES
# ============================================================================
def create_synthetic_dataset(n_users=100, n_items=50, sparsity=0.85, seed=42):
"""
Create synthetic movie rating dataset
Parameters
----------
n_users : int
Number of users
n_items : int
Number of movies
sparsity : float
Fraction of missing ratings
seed : int
Random seed
Returns
-------
np.ndarray : sparse rating matrix
"""
np.random.seed(seed)
rating_matrix = np.zeros((n_users, n_items))
# Generate ratings with realistic patterns
n_ratings = int(n_users * n_items * (1 - sparsity))
for _ in range(n_ratings):
user = np.random.randint(0, n_users)
item = np.random.randint(0, n_items)
# Bias toward certain ratings (more 3-5 star ratings)
rating = np.random.choice([1, 2, 3, 4, 5], p=[0.05, 0.1, 0.2, 0.35, 0.3])
rating_matrix[user, item] = rating
return rating_matrix
def get_movie_names(n_items=50):
"""Generate movie names"""
movies = [
"The Matrix", "Inception", "Interstellar", "The Dark Knight", "Pulp Fiction",
"Forrest Gump", "The Godfather", "Titanic", "Avatar", "Avengers",
"Gladiator", "Jurassic Park", "Shawshank Redemption", "Finding Nemo", "Toy Story",
"Star Wars", "Lord of the Rings", "Harry Potter", "Iron Man", "Captain America",
"Spider-Man", "Batman Begins", "Superman", "Wonder Woman", "Doctor Strange",
"Black Panther", "Aquaman", "The Flash", "Green Lantern", "Thor",
"Guardians Galaxy", "Ant-Man", "Captain Marvel", "Black Widow", "Eternals",
"Shang-Chi", "Spider-Verse", "Deadpool", "X-Men", "Fantastic Four",
"Dune", "Joker", "The Lighthouse", "Parasite", "1917",
"Tenet", "Oppenheimer", "Barbie", "Poor Things", "Godzilla"
]
return movies[:n_items]
# ============================================================================
# EVALUATION METRICS
# ============================================================================
class RecommenderEvaluator:
"""Comprehensive evaluation of recommender system"""
def __init__(self, model, rating_matrix, movie_names):
self.model = model
self.rating_matrix = rating_matrix
self.movie_names = movie_names
def rmse(self):
"""Return final RMSE"""
return self.model.rmse_history[-1] if self.model.rmse_history else None
def mean_average_precision(self, k=10):
"""Mean Average Precision @ k"""
n_users = self.rating_matrix.shape[0]
ap_scores = []
for user_id in range(n_users):
recs = self.model.get_recommendations(user_id, n_recommendations=k)
if not recs:
continue
# Items user rated highly (≥4)
relevant = np.where(self.rating_matrix[user_id] >= 4)[0]
if len(relevant) == 0:
continue
rec_items = [item_id for item_id, _ in recs]
# Precision at each position
precisions = []
hits = 0
for i, item_id in enumerate(rec_items):
if item_id in relevant:
hits += 1
precisions.append(hits / (i + 1))
if precisions:
ap_scores.append(np.mean(precisions))
return np.mean(ap_scores) if ap_scores else 0.0
def recall_at_k(self, k=10):
"""Recall @ k"""
n_users = self.rating_matrix.shape[0]
recalls = []
for user_id in range(n_users):
recs = self.model.get_recommendations(user_id, n_recommendations=k)
relevant = np.where(self.rating_matrix[user_id] >= 4)[0]
if len(relevant) == 0:
continue
rec_items = [item_id for item_id, _ in recs]
hits = len(set(rec_items) & set(relevant))
recalls.append(hits / len(relevant))
return np.mean(recalls) if recalls else 0.0
def catalog_coverage(self, k=5):
"""Fraction of catalog recommended"""
n_users = self.rating_matrix.shape[0]
recommended = set()
for user_id in range(n_users):
recs = self.model.get_recommendations(user_id, n_recommendations=k)
recommended.update(item_id for item_id, _ in recs)
return len(recommended) / self.rating_matrix.shape[1]
def recommendation_diversity(self, k=5):
"""Average pairwise distance between recommendations"""
n_users = self.rating_matrix.shape[0]
diversities = []
for user_id in range(n_users):
recs = self.model.get_recommendations(user_id, n_recommendations=k)
if len(recs) < 2:
continue
rec_items = [item_id for item_id, _ in recs]
item_vecs = self.model.item_matrix[rec_items]
# Average pairwise distance
distances = []
for i in range(len(rec_items)):
for j in range(i+1, len(rec_items)):
dist = np.linalg.norm(item_vecs[i] - item_vecs[j])
distances.append(dist)
if distances:
diversities.append(np.mean(distances))
return np.mean(diversities) if diversities else 0.0
def print_report(self, k=10):
"""Print comprehensive evaluation report"""
print("\n" + "="*70)
print("RECOMMENDER SYSTEM EVALUATION REPORT")
print("="*70)
print(f"\n📊 PREDICTION ACCURACY:")
print(f" RMSE: {self.rmse():.6f}")
print(f"\n🎯 RANKING QUALITY (Top-{k}):")
print(f" MAP (Mean Average Precision): {self.mean_average_precision(k):.4f}")
print(f" Recall@{k}: {self.recall_at_k(k):.4f}")
print(f"\n🌈 DIVERSITY & COVERAGE:")
print(f" Catalog Coverage: {self.catalog_coverage(k):.1%}")
print(f" Recommendation Diversity: {self.recommendation_diversity(k):.4f}")
print("="*70)
# ============================================================================
# VISUALIZATION
# ============================================================================
def plot_analysis(model, rating_matrix, movie_names):
"""Create comprehensive analysis plots"""
fig = plt.figure(figsize=(16, 12))
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
# 1. RMSE Convergence
ax = fig.add_subplot(gs[0, :2])
iterations = range(1, len(model.rmse_history) + 1)
ax.plot(iterations, model.rmse_history, 'b-', linewidth=2.5, marker='o', markersize=4)
ax.fill_between(iterations, model.rmse_history, alpha=0.2)
ax.set_xlabel('Iteration', fontsize=11, fontweight='bold')
ax.set_ylabel('RMSE', fontsize=11, fontweight='bold')
ax.set_title('Training Convergence', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.set_yscale('log')
# 2. RMSE Improvement
ax = fig.add_subplot(gs[0, 2])
improvements = np.diff([model.rmse_history[0]] + model.rmse_history)
ax.bar(range(len(improvements)), -improvements, color='green', alpha=0.6)
ax.set_xlabel('Iteration', fontsize=11, fontweight='bold')
ax.set_ylabel('RMSE Improvement', fontsize=11, fontweight='bold')
ax.set_title('Iteration Gains', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3, axis='y')
# 3. Actual vs Predicted
ax = fig.add_subplot(gs[1, 0])
predictions = model.predict_all()
observed = rating_matrix != 0
ax.scatter(rating_matrix[observed], predictions[observed],
alpha=0.5, s=20, edgecolor='none')
ax.plot([1, 5], [1, 5], 'r--', linewidth=2, label='Perfect')
ax.set_xlabel('Actual Rating', fontsize=11, fontweight='bold')
ax.set_ylabel('Predicted Rating', fontsize=11, fontweight='bold')
ax.set_title('Prediction Accuracy', fontsize=12, fontweight='bold')
ax.set_xlim(0.5, 5.5)
ax.set_ylim(0.5, 5.5)
ax.legend()
ax.grid(True, alpha=0.3)
# 4. Residual Distribution
ax = fig.add_subplot(gs[1, 1])
errors = (rating_matrix[observed] - predictions[observed])
ax.hist(errors, bins=30, color='purple', alpha=0.7, edgecolor='black')
ax.axvline(errors.mean(), color='red', linestyle='--', linewidth=2, label=f'μ={errors.mean():.3f}')
ax.set_xlabel('Prediction Error', fontsize=11, fontweight='bold')
ax.set_ylabel('Frequency', fontsize=11, fontweight='bold')
ax.set_title('Error Distribution', fontsize=12, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3, axis='y')
# 5. Error Statistics
ax = fig.add_subplot(gs[1, 2])
ax.axis('off')
error_stats = f"""ERROR STATISTICS
Mean: {errors.mean():.4f}
Std Dev: {errors.std():.4f}
Min: {errors.min():.4f}
Max: {errors.max():.4f}
MAE: {np.abs(errors).mean():.4f}
Median: {np.median(errors):.4f}
Q1: {np.percentile(errors, 25):.4f}
Q3: {np.percentile(errors, 75):.4f}"""
ax.text(0.1, 0.5, error_stats, fontsize=10, family='monospace',
verticalalignment='center', bbox=dict(boxstyle='round',
facecolor='wheat', alpha=0.5))
# 6. User Embeddings (2D projection)
ax = fig.add_subplot(gs[2, 0])
user_2d = model.user_matrix[:, :2]
scatter = ax.scatter(user_2d[:, 0], user_2d[:, 1],
c=np.arange(len(user_2d)), cmap='viridis',
s=100, alpha=0.6, edgecolor='black', linewidth=0.5)
ax.set_xlabel('Factor 1', fontsize=11, fontweight='bold')
ax.set_ylabel('Factor 2', fontsize=11, fontweight='bold')
ax.set_title('User Latent Factors', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
plt.colorbar(scatter, ax=ax, label='User ID')
# 7. Item Embeddings (2D projection)
ax = fig.add_subplot(gs[2, 1])
item_2d = model.item_matrix[:, :2]
scatter = ax.scatter(item_2d[:, 0], item_2d[:, 1],
c=np.arange(len(item_2d)), cmap='plasma',
s=100, alpha=0.6, edgecolor='black', linewidth=0.5)
ax.set_xlabel('Factor 1', fontsize=11, fontweight='bold')
ax.set_ylabel('Factor 2', fontsize=11, fontweight='bold')
ax.set_title('Item Latent Factors', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
plt.colorbar(scatter, ax=ax, label='Item ID')
# 8. Sparsity Pattern
ax = fig.add_subplot(gs[2, 2])
sparsity_by_user = (rating_matrix != 0).sum(axis=1)
ax.hist(sparsity_by_user, bins=20, color='teal', alpha=0.7, edgecolor='black')
ax.axvline(sparsity_by_user.mean(), color='red', linestyle='--',
linewidth=2, label=f'μ={sparsity_by_user.mean():.1f}')
ax.set_xlabel('Ratings per User', fontsize=11, fontweight='bold')
ax.set_ylabel('Number of Users', fontsize=11, fontweight='bold')
ax.set_title('Rating Distribution', fontsize=12, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3, axis='y')
plt.savefig('als_analysis.png', dpi=300, bbox_inches='tight')
print("\n✓ Visualization saved as 'als_analysis.png'")
plt.show()
# ============================================================================
# MAIN EXECUTION
# ============================================================================
def main():
print("\n" + "="*70)
print("🎬 MOVIE RECOMMENDER SYSTEM WITH ALTERNATING LEAST SQUARES")
print("="*70)
# Create dataset
print("\n📥 Creating Synthetic Dataset...")
n_users, n_items = 100, 50
rating_matrix = create_synthetic_dataset(n_users, n_items, sparsity=0.90)
movie_names = get_movie_names(n_items)
n_ratings = (rating_matrix != 0).sum()
sparsity = 1 - n_ratings / (n_users * n_items)
print(f" Users: {n_users}")
print(f" Movies: {n_items}")
print(f" Ratings: {n_ratings}")
print(f" Sparsity: {sparsity:.1%}")
print(f" Mean Rating: {rating_matrix[rating_matrix != 0].mean():.2f}/5.0")
# Train model
print("\n" + "="*70)
print("⚙️ TRAINING ALS MODEL")
print("="*70)
model = ALSMatrixFactorization(
n_factors=15,
lambda_reg=0.05,
max_iterations=50,
convergence_threshold=0.0001,
verbose=True
)
model.fit(rating_matrix)
# Evaluate
print("\n" + "="*70)
print("📈 EVALUATION")
print("="*70)
evaluator = RecommenderEvaluator(model, rating_matrix, movie_names)
evaluator.print_report(k=10)
# Sample recommendations
print("\n" + "="*70)
print("🎯 SAMPLE RECOMMENDATIONS")
print("="*70)
for user_id in range(3):
print(f"\n👤 User {user_id}:")
# Rated movies
rated_idx = np.where(rating_matrix[user_id] != 0)[0]
if len(rated_idx) > 0:
print(f" Previously Rated ({len(rated_idx)} movies):")
rated_with_scores = [(movie_names[i], rating_matrix[user_id, i])
for i in rated_idx]
rated_with_scores.sort(key=lambda x: x[1], reverse=True)
for movie, score in rated_with_scores[:3]:
print(f" • {movie}: {'⭐' * int(score)}")
if len(rated_idx) > 3:
print(f" ... and {len(rated_idx)-3} more")
# Recommendations
recs = model.get_recommendations(user_id, n_recommendations=5)
print(f" 🎬 Top 5 Recommendations:")
for rank, (item_id, score) in enumerate(recs, 1):
stars = min(5, max(1, int(round(score))))
print(f" {rank}. {movie_names[item_id]}: {score:.2f}/5 {'⭐' * stars}")
# Visualization
print("\n" + "="*70)
print("📊 GENERATING VISUALIZATIONS")
print("="*70)
plot_analysis(model, rating_matrix, movie_names)
# Advanced statistics
print("\n" + "="*70)
print("📋 ADVANCED STATISTICS")
print("="*70)
predictions = model.predict_all()
observed = rating_matrix != 0
print(f"\n📊 Prediction Statistics:")
print(f" Mean Predicted Rating: {predictions[observed].mean():.2f}")
print(f" Std Dev: {predictions[observed].std():.2f}")
print(f" Min: {predictions[observed].min():.2f}")
print(f" Max: {predictions[observed].max():.2f}")
print(f"\n🎞️ Top 5 Most Popular Movies:")
popularity = (rating_matrix != 0).sum(axis=0)
top_movies = np.argsort(popularity)[::-1][:5]
for rank, item_id in enumerate(top_movies, 1):
avg_rating = rating_matrix[rating_matrix[:, item_id] != 0, item_id].mean()
print(f" {rank}. {movie_names[item_id]}: {popularity[item_id]} ratings, "
f"avg {avg_rating:.2f}/5")
print(f"\n👥 Top 5 Most Active Users:")
activity = (rating_matrix != 0).sum(axis=1)
top_users = np.argsort(activity)[::-1][:5]
for rank, user_id in enumerate(top_users, 1):
avg_rating = rating_matrix[user_id, rating_matrix[user_id] != 0].mean()
print(f" {rank}. User {user_id}: {activity[user_id]} ratings, "
f"avg {avg_rating:.2f}/5")
print("\n" + "="*70)
print("✅ Analysis Complete!")
print("="*70 + "\n")
return model, rating_matrix, movie_names
if __name__ == "__main__":
model, rating_matrix, movie_names = main()
Usage & Key Features
Core Components:
- ALS Algorithm: Iteratively solves least squares problems for users and items
- Convergence Tracking: Monitors RMSE improvement and stops when converged
- Regularization: L2 regularization prevents overfitting
- Sparse Matrix Handling: Only operates on observed ratings
Evaluation Metrics:
# After training:
evaluator = RecommenderEvaluator(model, rating_matrix, movie_names)
# Get metrics
rmse = evaluator.rmse()
map_score = evaluator.mean_average_precision(k=10)
recall = evaluator.recall_at_k(k=10)
coverage = evaluator.catalog_coverage()
diversity = evaluator.recommendation_diversity()
Making Predictions:
# Single prediction
score = model.predict(user_id=0, item_id=5)
# Get recommendations
recommendations = model.get_recommendations(user_id=0, n_recommendations=5)
# Returns: [(item_id, predicted_rating), ...]
# Full prediction matrix
all_predictions = model.predict_all()
Output Includes:
- ✅ Real-time convergence monitoring with RMSE tracking
- ✅ User and item latent factor embeddings (visualized in 2D)
- ✅ Actual vs. predicted rating scatter plots
- ✅ Recommendation quality metrics
- ✅ Catalog coverage and diversity analysis
- ✅ Personalized movie recommendations for each user
The visualization displays training convergence, prediction accuracy, latent factor distributions, and recommendation quality!