-
Notifications
You must be signed in to change notification settings - Fork 0
/
SparseLinearKernel.cs
75 lines (60 loc) · 1.4 KB
/
SparseLinearKernel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grammophone.Vectors;
namespace Grammophone.Kernels
{
/// <summary>
/// The simplest kernel, the dot product between two sparse vectors.
/// </summary>
[Serializable]
public class SparseLinearKernel : Kernel<SparseVector>
{
#region Private fields
private SparseVector componentAccumulator;
#endregion
#region Kernel<T> implementation
public override bool HasComponents
{
get
{
return this.componentAccumulator != null;
}
}
public override double Compute(SparseVector arg1, SparseVector arg2)
{
if (arg1 == arg2) return arg1.Norm2;
return arg1 * arg2;
}
public override double ComputeSum(SparseVector arg)
{
if (arg == null) throw new ArgumentNullException("arg");
if (this.componentAccumulator == null)
return 0.0;
else
return arg * this.componentAccumulator;
}
public override void AddComponent(double weight, SparseVector arg)
{
if (arg == null) throw new ArgumentNullException("arg");
if (this.componentAccumulator == null)
{
this.componentAccumulator = weight * arg;
}
else
{
this.componentAccumulator += weight * arg;
}
}
public override void ClearComponents()
{
this.componentAccumulator = null;
}
public override Kernel<SparseVector> ForkNew()
{
return new SparseLinearKernel();
}
#endregion
}
}