forked from bwaldvogel/liblinear-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL2LrFunction.java
More file actions
116 lines (92 loc) · 2.34 KB
/
Copy pathL2LrFunction.java
File metadata and controls
116 lines (92 loc) · 2.34 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
package liblinear;
class L2LrFunction implements Function {
private final double[] C;
private final double[] z;
private final double[] D;
private final Problem prob;
public L2LrFunction( Problem prob, double Cp, double Cn ) {
int i;
int l = prob.l;
int[] y = prob.y;
this.prob = prob;
z = new double[l];
D = new double[l];
C = new double[l];
for ( i = 0; i < l; i++ ) {
if ( y[i] == 1 )
C[i] = Cp;
else
C[i] = Cn;
}
}
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;
}
}
}
private void XTv( double[] v, double[] XTv ) {
int l = prob.l;
int n = prob.n;
FeatureNode[][] x = prob.x;
for ( int i = 0; i < n; i++ )
XTv[i] = 0;
for ( int i = 0; i < l; i++ ) {
for ( FeatureNode s : x[i] ) {
XTv[s.index - 1] += v[i] * s.value;
}
}
}
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++ ) {
double yz = y[i] * z[i];
if ( yz >= 0 )
f += C[i] * Math.log(1 + Math.exp(-yz));
else
f += C[i] * (-yz + Math.log(1 + Math.exp(yz)));
}
f = 2.0 * f;
for ( i = 0; i < n; i++ )
f += w[i] * w[i];
f /= 2.0;
return (f);
}
public void grad( double[] w, double[] g ) {
int i;
int[] y = prob.y;
int l = prob.l;
int n = prob.n;
for ( i = 0; i < l; i++ ) {
z[i] = 1 / (1 + Math.exp(-y[i] * z[i]));
D[i] = z[i] * (1 - z[i]);
z[i] = C[i] * (z[i] - 1) * y[i];
}
XTv(z, g);
for ( i = 0; i < n; i++ )
g[i] = w[i] + g[i];
}
public void Hv( double[] s, double[] Hs ) {
int i;
int l = prob.l;
int n = prob.n;
double[] wa = new double[l];
Xv(s, wa);
for ( i = 0; i < l; i++ )
wa[i] = C[i] * D[i] * wa[i];
XTv(wa, Hs);
for ( i = 0; i < n; i++ )
Hs[i] = s[i] + Hs[i];
// delete[] wa;
}
public int get_nr_variable() {
return prob.n;
}
}