矩陣分解(Matrix Factorization)是一種常用的協同過濾(Collaborative Filtering, CF)算法,常用于推薦系統中。下面是一個基于矩陣分解的CF算法的實現示例:
import numpy as np
class MatrixFactorizationCF:
def __init__(self, num_users, num_items, num_factors=10, learning_rate=0.01, reg_param=0.01, num_iterations=100):
self.num_users = num_users
self.num_items = num_items
self.num_factors = num_factors
self.learning_rate = learning_rate
self.reg_param = reg_param
self.num_iterations = num_iterations
self.user_factors = None
self.item_factors = None
def fit(self, train_data):
# 初始化用戶和物品的隱因子矩陣
self.user_factors = np.random.normal(scale=1./self.num_factors, size=(self.num_users, self.num_factors))
self.item_factors = np.random.normal(scale=1./self.num_factors, size=(self.num_items, self.num_factors))
for iteration in range(self.num_iterations):
for user_id, item_id, rating in train_data:
error = rating - self.predict(user_id, item_id)
# 更新用戶和物品的隱因子矩陣
self.user_factors[user_id] += self.learning_rate * (error * self.item_factors[item_id] - self.reg_param * self.user_factors[user_id])
self.item_factors[item_id] += self.learning_rate * (error * self.user_factors[user_id] - self.reg_param * self.item_factors[item_id])
def predict(self, user_id, item_id):
return np.dot(self.user_factors[user_id], self.item_factors[item_id])
使用示例:
# 創建一個矩陣分解的CF模型
cf_model = MatrixFactorizationCF(num_users=100, num_items=50, num_factors=10, learning_rate=0.01, reg_param=0.01, num_iterations=100)
# 使用訓練數據訓練模型
train_data = [(0, 0, 5), (1, 1, 3), (2, 2, 4), ...]
cf_model.fit(train_data)
# 預測用戶0對物品1的評分
user_id = 0
item_id = 1
predicted_rating = cf_model.predict(user_id, item_id)
print("Predicted rating for user", user_id, "and item", item_id, ":", predicted_rating)
以上示例演示了如何使用基于矩陣分解的CF算法對用戶對物品的評分進行預測。在fit方法中,通過迭代優化用戶和物品的隱因子矩陣,來逼近真實的評分數據。然后使用predict方法來預測用戶對物品的評分。