forked from bwaldvogel/liblinear-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL2LossSVMFunction.java
More file actions
125 lines (100 loc) · 2.51 KB
/
Copy pathL2LossSVMFunction.java
File metadata and controls
125 lines (100 loc) · 2.51 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package liblinear;
public class L2LossSVMFunction implements Function {
private final Problem prob;
private final double[] C;
private final int[] I;
private final double[] z;
private int sizeI;
public L2LossSVMFunction( Problem prob, double Cp, double Cn ) {
int i;
int l = prob.l;
int[] y = prob.y;
this.prob = prob;
z = new double[l];
C = new double[l];
I = new int[l];
for ( i = 0; i < l; i++ ) {
if ( y[i] == 1 )
C[i] = Cp;
else
C[i] = Cn;
}
}
public double fun( double[] w ) {
int i;
double f = 0;
int[] y = prob.y;
int l = prob.l;
int n = prob.n;
Xv(w, z);
for ( i = 0; i < l; i++ ) {
z[i] = y[i] * z[i];
double d = 1 - z[i];
if ( d > 0 ) f += C[i] * d * d;
}
f = 2 * f;
for ( i = 0; i < n; i++ )
f += w[i] * w[i];
f /= 2.0;
return (f);
}
public int get_nr_variable() {
return prob.n;
}
public void grad( double[] w, double[] g ) {
int i;
int[] y = prob.y;
int l = prob.l;
int n = prob.n;
sizeI = 0;
for ( i = 0; i < l; i++ ) {
if ( z[i] < 1 ) {
z[sizeI] = C[i] * y[i] * (z[i] - 1);
I[sizeI] = i;
sizeI++;
}
}
subXTv(z, g);
for ( i = 0; i < n; i++ )
g[i] = w[i] + 2 * g[i];
}
public void Hv( double[] s, double[] Hs ) {
int i;
int l = prob.l;
int n = prob.n;
double[] wa = new double[l];
subXv(s, wa);
for ( i = 0; i < sizeI; i++ )
wa[i] = C[I[i]] * wa[i];
subXTv(wa, Hs);
for ( i = 0; i < n; i++ )
Hs[i] = s[i] + 2 * Hs[i];
}
private void subXTv( double[] v, double[] XTv ) {
int i;
int n = prob.n;
for ( i = 0; i < n; i++ )
XTv[i] = 0;
for ( i = 0; i < sizeI; i++ ) {
for ( FeatureNode s : prob.x[I[i]] ) {
XTv[s.index - 1] += v[i] * s.value;
}
}
}
private void subXv( double[] v, double[] Xv ) {
for ( int i = 0; i < sizeI; i++ ) {
Xv[i] = 0;
for ( FeatureNode s : prob.x[I[i]] ) {
Xv[i] += v[s.index - 1] * s.value;
}
}
}
private void Xv( double[] v, double[] Xv ) {
for ( int i = 0; i < prob.l; i++ ) {
Xv[i] = 0;
for ( FeatureNode s : prob.x[i] ) {
Xv[i] += v[s.index - 1] * s.value;
}
}
}
}