Slope One 是一種簡單高效的**項目基礎協同過濾**演算法,核心假設:任兩項目之間的平均評分差值固定,利用所有使用者的共同評分歷史預測目標使用者對未評分項目的偏好。本文提供完整、可直接編譯執行的 C# 實作。
public class Rating
{
public float Value { get; set; } // 累積評分差
public int Freq { get; set; } // 共同評分次數
public float AverageValue => Value / Freq; // 平均差值
}
// 雙向鍵值對:Item1Id/Item2Id (較小在前) -> Rating
public class RatingDifferenceCollection : Dictionary
{
private string Key(int i1, int i2) => (i1 < i2) ? $"{i1}/{i2}" : $"{i2}/{i1}";
public bool Contains(int i1, int i2) => ContainsKey(Key(i1, i2));
public Rating this[int i1, int i2]
{
get => this[Key(i1, i2)];
set => this[Key(i1, i2)] = value;
}
}
public class SlopeOne
{
public RatingDifferenceCollection DiffMatrix { get; } = new RatingDifferenceCollection();
public HashSet Items { get; } = new HashSet(); // 所有項目 ID
// 加入單一使用者評分字典
public void AddUserRatings(IDictionary userRatings)
{
foreach (var (item1Id, rating1) in userRatings)
{
Items.Add(item1Id);
foreach (var (item2Id, rating2) in userRatings)
{
if (item2Id <= item1Id) continue; // 避免重複配對 (i,j) & (j,i)
var diff = rating1 - rating2;
if (DiffMatrix.Contains(item1Id, item2Id))
{
var r = DiffMatrix[item1Id, item2Id];
r.Value += diff;
r.Freq++;
}
else
{
DiffMatrix[item1Id, item2Id] = new Rating { Value = diff, Freq = 1 };
}
}
}
}
// 批次加入多使用者
public void AddUsersRatings(IEnumerable> allRatings)
{
foreach (var ur in allRatings) AddUserRatings(ur);
}
// 預測目標使用者對所有未評分項目的評分
public IDictionary Predict(IDictionary userRatings)
{
var predictions = new Dictionary();
foreach (var itemId in Items)
{
if (userRatings.ContainsKey(itemId)) continue; // 已評分跳過
var numerator = 0f;
var denominator = 0;
foreach (var (ratedItem, ratedScore) in userRatings)
{
if (!DiffMatrix.Contains(itemId, ratedItem)) continue;
var diff = DiffMatrix[itemId, ratedItem];
numerator += (ratedScore + diff.AverageValue) * diff.Freq;
denominator += diff.Freq;
}
if (denominator > 0)
predictions[itemId] = numerator / denominator;
}
return predictions;
}
}
var engine = new SlopeOne();
// 訓練資料:多位使用者的評分
var training = new List>
{
new() { {1, 5f}, {2, 3f}, {3, 4f} },
new() { {1, 4f}, {2, 2f}, {4, 5f} },
new() { {2, 4f}, {3, 5f}, {4, 3f} },
};
engine.AddUsersRatings(training);
// 目標使用者已評分項目
var targetUser = new Dictionary { {1, 5f}, {3, 4f} };
// 預測項目 2、4 的評分
var preds = engine.Predict(targetUser);
foreach (var (item, score) in preds.OrderByDescending(p => p.Value))
{
Console.WriteLine($"Item {item}: predicted rating = {score:F2}");
}
| 階段 | 時間複雜度 | 空間複雜度 |
|---|---|---|
| 建模 (AddUserRatings) | O(U * I²) U=用戶數, I=平均評分項目數 | O(I²) 項目配對差值矩陣 |
| 預測 | O(I * R) R=目標用戶已評分數 | O(I) 預測結果 |