当前位置: 编程技术>.net/c#/asp.net
C#实现协同过滤算法的实例代码
来源: 互联网 发布时间:2014-10-22
本文导语: 代码如下:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SlopeOne{ public class Rating { public float Value { get; set; } public int Freq { get; set; } public float AverageValue { ...
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SlopeOne
{
public class Rating
{
public float Value { get; set; }
public int Freq { get; set; }
public float AverageValue
{
get { return Value / Freq; }
}
}
public class RatingDifferenceCollection : Dictionary
{
private string GetKey(int Item1Id, int Item2Id)
{
return (Item1Id < Item2Id) ? Item1Id + "/" + Item2Id : Item2Id + "/" + Item1Id ;
}
public bool Contains(int Item1Id, int Item2Id)
{
return this.Keys.Contains(GetKey(Item1Id, Item2Id));
}
public Rating this[int Item1Id, int Item2Id]
{
get {
return this[this.GetKey(Item1Id, Item2Id)];
}
set { this[this.GetKey(Item1Id, Item2Id)] = value; }
}
}
public class SlopeOne
{
public RatingDifferenceCollection _DiffMarix = new RatingDifferenceCollection(); // The dictionary to keep the diff matrix
public HashSet _Items = new HashSet(); // Tracking how many items totally
public void AddUserRatings(IDictionary userRatings)
{
foreach (var item1 in userRatings)
{
int item1Id = item1.Key;
float item1Rating = item1.Value;
_Items.Add(item1.Key);
foreach (var item2 in userRatings)
{
if (item2.Key