This repository has been archived by the owner on Sep 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 119
/
NDCGUDAF.java
276 lines (232 loc) · 11.4 KB
/
NDCGUDAF.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
* 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 hivemall.evaluation;
import hivemall.utils.hadoop.HiveUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AbstractAggregationBuffer;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableDoubleObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableIntObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.io.LongWritable;
@Description(
name = "ndcg",
value = "_FUNC_(array rankItems, array correctItems [, const int recommendSize = rankItems.size])"
+ " - Returns nDCG")
public final class NDCGUDAF extends AbstractGenericUDAFResolver {
// prevent instantiation
private NDCGUDAF() {}
@Override
public GenericUDAFEvaluator getEvaluator(@Nonnull TypeInfo[] typeInfo) throws SemanticException {
if (typeInfo.length != 2 && typeInfo.length != 3) {
throw new UDFArgumentTypeException(typeInfo.length - 1,
"_FUNC_ takes two or three arguments");
}
ListTypeInfo arg1type = HiveUtils.asListTypeInfo(typeInfo[0]);
if (!HiveUtils.isPrimitiveTypeInfo(arg1type.getListElementTypeInfo())
&& !HiveUtils.isStructTypeInfo(arg1type.getListElementTypeInfo())) {
throw new UDFArgumentTypeException(0,
"The first argument `array rankItems` is invalid form: " + typeInfo[0]);
}
ListTypeInfo arg2type = HiveUtils.asListTypeInfo(typeInfo[1]);
if (!HiveUtils.isPrimitiveTypeInfo(arg2type.getListElementTypeInfo())) {
throw new UDFArgumentTypeException(1,
"The first argument `array rankItems` is invalid form: " + typeInfo[1]);
}
return new Evaluator();
}
public static class Evaluator extends GenericUDAFEvaluator {
private ListObjectInspector recommendListOI;
private ListObjectInspector truthListOI;
private WritableIntObjectInspector recommendSizeOI;
private StructObjectInspector internalMergeOI;
private StructField countField;
private StructField sumField;
public Evaluator() {}
@Override
public ObjectInspector init(Mode mode, ObjectInspector[] parameters) throws HiveException {
assert (parameters.length == 2 || parameters.length == 3) : parameters.length;
super.init(mode, parameters);
// initialize input
if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) {// from original data
this.recommendListOI = (ListObjectInspector) parameters[0];
this.truthListOI = (ListObjectInspector) parameters[1];
if (parameters.length == 3) {
this.recommendSizeOI = (WritableIntObjectInspector) parameters[2];
}
} else {// from partial aggregation
StructObjectInspector soi = (StructObjectInspector) parameters[0];
this.internalMergeOI = soi;
this.countField = soi.getStructFieldRef("count");
this.sumField = soi.getStructFieldRef("sum");
}
// initialize output
final ObjectInspector outputOI;
if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) {// terminatePartial
outputOI = internalMergeOI();
} else {// terminate
outputOI = PrimitiveObjectInspectorFactory.writableDoubleObjectInspector;
}
return outputOI;
}
private static StructObjectInspector internalMergeOI() {
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
fieldNames.add("sum");
fieldOIs.add(PrimitiveObjectInspectorFactory.writableDoubleObjectInspector);
fieldNames.add("count");
fieldOIs.add(PrimitiveObjectInspectorFactory.writableLongObjectInspector);
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
}
@Override
public NDCGAggregationBuffer getNewAggregationBuffer() throws HiveException {
NDCGAggregationBuffer myAggr = new NDCGAggregationBuffer();
reset(myAggr);
return myAggr;
}
@Override
public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg)
throws HiveException {
NDCGAggregationBuffer myAggr = (NDCGAggregationBuffer) agg;
myAggr.reset();
}
@Override
public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg,
Object[] parameters) throws HiveException {
NDCGAggregationBuffer myAggr = (NDCGAggregationBuffer) agg;
List<?> recommendList = recommendListOI.getList(parameters[0]);
if (recommendList == null) {
recommendList = Collections.emptyList();
}
List<?> truthList = truthListOI.getList(parameters[1]);
if (truthList == null) {
return;
}
int recommendSize = recommendList.size();
if (parameters.length == 3) {
recommendSize = recommendSizeOI.get(parameters[2]);
}
if (recommendSize < 0 || recommendSize > recommendList.size()) {
throw new UDFArgumentException(
"The third argument `int recommendSize` must be in [0, " + recommendList.size()
+ "]");
}
boolean isBinary = !HiveUtils.isStructOI(recommendListOI.getListElementObjectInspector());
double ndcg = 0.0d;
if (isBinary) {
ndcg = BinaryResponsesMeasures.nDCG(recommendList, truthList, recommendSize);
} else {
// Create a ordered list of relevance scores for recommended items
List<Double> recommendRelScoreList = new ArrayList<Double>();
StructObjectInspector sOI = (StructObjectInspector) recommendListOI.getListElementObjectInspector();
List<?> fieldRefList = sOI.getAllStructFieldRefs();
StructField relScoreField = (StructField) fieldRefList.get(0);
WritableDoubleObjectInspector relScoreFieldOI = (WritableDoubleObjectInspector) relScoreField.getFieldObjectInspector();
for (int i = 0, n = recommendList.size(); i < n; i++) {
Object structObj = recommendList.get(i);
List<Object> fieldList = sOI.getStructFieldsDataAsList(structObj);
double relScore = (double) relScoreFieldOI.get(fieldList.get(0));
recommendRelScoreList.add(relScore);
}
// Create a ordered list of relevance scores for truth items
List<Double> truthRelScoreList = new ArrayList<Double>();
WritableDoubleObjectInspector truthRelScoreOI = (WritableDoubleObjectInspector) truthListOI.getListElementObjectInspector();
for (int i = 0, n = truthList.size(); i < n; i++) {
Object relScoreObj = truthList.get(i);
double relScore = (double) truthRelScoreOI.get(relScoreObj);
truthRelScoreList.add(relScore);
}
ndcg = GradedResponsesMeasures.nDCG(recommendRelScoreList, truthRelScoreList,
recommendSize);
}
myAggr.iterate(ndcg);
}
@Override
public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg)
throws HiveException {
NDCGAggregationBuffer myAggr = (NDCGAggregationBuffer) agg;
Object[] partialResult = new Object[2];
partialResult[0] = new DoubleWritable(myAggr.sum);
partialResult[1] = new LongWritable(myAggr.count);
return partialResult;
}
@Override
public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object partial)
throws HiveException {
if (partial == null) {
return;
}
Object sumObj = internalMergeOI.getStructFieldData(partial, sumField);
Object countObj = internalMergeOI.getStructFieldData(partial, countField);
double sum = PrimitiveObjectInspectorFactory.writableDoubleObjectInspector.get(sumObj);
long count = PrimitiveObjectInspectorFactory.writableLongObjectInspector.get(countObj);
NDCGAggregationBuffer myAggr = (NDCGAggregationBuffer) agg;
myAggr.merge(sum, count);
}
@Override
public DoubleWritable terminate(@SuppressWarnings("deprecation") AggregationBuffer agg)
throws HiveException {
NDCGAggregationBuffer myAggr = (NDCGAggregationBuffer) agg;
double result = myAggr.get();
return new DoubleWritable(result);
}
}
public static class NDCGAggregationBuffer extends AbstractAggregationBuffer {
double sum;
long count;
public NDCGAggregationBuffer() {
super();
}
void reset() {
this.sum = 0.d;
this.count = 0;
}
void merge(double o_sum, long o_count) {
sum += o_sum;
count += o_count;
}
double get() {
if (count == 0) {
return 0.d;
}
return sum / count;
}
void iterate(@Nonnull double ndcg) {
sum += ndcg;
count++;
}
}
}