-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
BaggingTest.java
242 lines (208 loc) · 8.95 KB
/
BaggingTest.java
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.composition.bagging;
import org.apache.ignite.ml.IgniteModel;
import org.apache.ignite.ml.TestUtils;
import org.apache.ignite.ml.common.TrainerTest;
import org.apache.ignite.ml.composition.combinators.parallel.ModelsParallelComposition;
import org.apache.ignite.ml.composition.predictionsaggregator.MeanValuePredictionsAggregator;
import org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator;
import org.apache.ignite.ml.dataset.Dataset;
import org.apache.ignite.ml.dataset.DatasetBuilder;
import org.apache.ignite.ml.environment.LearningEnvironment;
import org.apache.ignite.ml.environment.LearningEnvironmentBuilder;
import org.apache.ignite.ml.math.functions.IgniteTriFunction;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.math.primitives.vector.VectorUtils;
import org.apache.ignite.ml.nn.UpdatesStrategy;
import org.apache.ignite.ml.optimization.updatecalculators.SimpleGDParameterUpdate;
import org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator;
import org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel;
import org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer;
import org.apache.ignite.ml.trainers.AdaptableDatasetModel;
import org.apache.ignite.ml.trainers.DatasetTrainer;
import org.apache.ignite.ml.trainers.FeatureLabelExtractor;
import org.apache.ignite.ml.trainers.TrainerTransformers;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Tests for bagging algorithm.
*/
public class BaggingTest extends TrainerTest {
/**
* Dependency of weights of first model in ensemble after training in
* {@link BaggingTest#testNaiveBaggingLogRegression()}. This dependency is tested to ensure that it is
* fully determined by provided seeds.
*/
private static Map<Integer, Vector> firstModelWeights;
static {
firstModelWeights = new HashMap<>();
firstModelWeights.put(1, VectorUtils.of(-0.14721735583126058, 4.366377931980097));
firstModelWeights.put(2, VectorUtils.of(-1.0092940937477968, 1.2950461550870134));
firstModelWeights.put(3, VectorUtils.of(-5.5345231104301655, -0.7554216668724918));
firstModelWeights.put(4, VectorUtils.of(0.136489632011201, 1.0937407007786915));
firstModelWeights.put(13, VectorUtils.of(-0.27321382073998685, 1.1199411864901687));
}
/**
* Test that count of entries in context is equal to initial dataset size * subsampleRatio.
*/
@Test
public void testBaggingContextCount() {
count((ctxCount, countData, integer) -> ctxCount);
}
/**
* Test that count of entries in data is equal to initial dataset size * subsampleRatio.
*/
@Test
public void testBaggingDataCount() {
count((ctxCount, countData, integer) -> countData.cnt);
}
/**
* Test that bagged log regression makes correct predictions.
*/
@Test
public void testNaiveBaggingLogRegression() {
Map<Integer, Double[]> cacheMock = getCacheMock(twoLinearlySeparableClasses);
DatasetTrainer<LogisticRegressionModel, Double> trainer =
new LogisticRegressionSGDTrainer()
.withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2),
SimpleGDParameterUpdate::sumLocal, SimpleGDParameterUpdate::avg))
.withMaxIterations(30000)
.withLocIterations(100)
.withBatchSize(10)
.withSeed(123L);
BaggedTrainer<Double> baggedTrainer = TrainerTransformers.makeBagged(
trainer,
7,
0.7,
2,
2,
new OnMajorityPredictionsAggregator())
.withEnvironmentBuilder(TestUtils.testEnvBuilder());
BaggedModel mdl = baggedTrainer.fit(
cacheMock,
parts,
(k, v) -> VectorUtils.of(Arrays.copyOfRange(v, 1, v.length)),
(k, v) -> v[0]
);
Vector weights = ((LogisticRegressionModel)((AdaptableDatasetModel)((ModelsParallelComposition)((AdaptableDatasetModel)mdl
.model()).innerModel()).submodels().get(0)).innerModel()).weights();
TestUtils.assertEquals(firstModelWeights.get(parts), weights, 0.0);
TestUtils.assertEquals(0, mdl.predict(VectorUtils.of(100, 10)), PRECISION);
TestUtils.assertEquals(1, mdl.predict(VectorUtils.of(10, 100)), PRECISION);
}
/**
* Method used to test counts of data passed in context and in data builders.
*
* @param cntr Function specifying which data we should count.
*/
protected void count(IgniteTriFunction<Long, CountData, LearningEnvironment, Long> cntr) {
Map<Integer, Double[]> cacheMock = getCacheMock(twoLinearlySeparableClasses);
CountTrainer cntTrainer = new CountTrainer(cntr);
double subsampleRatio = 0.3;
BaggedModel mdl = TrainerTransformers.makeBagged(
cntTrainer,
100,
subsampleRatio,
2,
2,
new MeanValuePredictionsAggregator())
.fit(cacheMock,
parts,
(integer, doubles) -> VectorUtils.of(doubles),
(integer, doubles) -> doubles[doubles.length - 1]);
Double res = mdl.predict(null);
TestUtils.assertEquals(twoLinearlySeparableClasses.length * subsampleRatio, res, twoLinearlySeparableClasses.length / 10);
}
/**
* Get sum of two Long values each of which can be null.
*
* @param a First value.
* @param b Second value.
* @return Sum of parameters.
*/
protected static Long plusOfNullables(Long a, Long b) {
if (a == null)
return b;
if (b == null)
return a;
return a + b;
}
/**
* Trainer used to count entries in context or in data.
*/
protected static class CountTrainer extends DatasetTrainer<IgniteModel<Vector, Double>, Double> {
/**
* Function specifying which entries to count.
*/
private final IgniteTriFunction<Long, CountData, LearningEnvironment, Long> cntr;
/**
* Construct instance of this class.
*
* @param cntr Function specifying which entries to count.
*/
public CountTrainer(IgniteTriFunction<Long, CountData, LearningEnvironment, Long> cntr) {
this.cntr = cntr;
}
/** {@inheritDoc} */
@Override public <K, V> IgniteModel<Vector, Double> fit(
DatasetBuilder<K, V> datasetBuilder,
FeatureLabelExtractor<K, V, Double> extractor) {
Dataset<Long, CountData> dataset = datasetBuilder.build(
TestUtils.testEnvBuilder(),
(env, upstreamData, upstreamDataSize) -> upstreamDataSize,
(env, upstreamData, upstreamDataSize, ctx) -> new CountData(upstreamDataSize)
);
Long cnt = dataset.computeWithCtx(cntr, BaggingTest::plusOfNullables);
return x -> Double.valueOf(cnt);
}
/** {@inheritDoc} */
@Override public boolean isUpdateable(IgniteModel<Vector, Double> mdl) {
return true;
}
/** {@inheritDoc} */
@Override protected <K, V> IgniteModel<Vector, Double> updateModel(
IgniteModel<Vector, Double> mdl,
DatasetBuilder<K, V> datasetBuilder,
FeatureLabelExtractor<K, V, Double> extractor) {
return fit(datasetBuilder, extractor);
}
/** {@inheritDoc} */
@Override public CountTrainer withEnvironmentBuilder(LearningEnvironmentBuilder envBuilder) {
return (CountTrainer)super.withEnvironmentBuilder(envBuilder);
}
}
/** Data for count trainer. */
protected static class CountData implements AutoCloseable {
/** Counter. */
private long cnt;
/**
* Construct instance of this class.
*
* @param cnt Counter.
*/
public CountData(long cnt) {
this.cnt = cnt;
}
/** {@inheritDoc} */
@Override public void close() throws Exception {
// No-op
}
}
}