Skip to content

Instantly share code, notes, and snippets.

@myui
Created July 21, 2015 09:46
Show Gist options
  • Save myui/7f7141eb6d4583b6582a to your computer and use it in GitHub Desktop.
Save myui/7f7141eb6d4583b6582a to your computer and use it in GitHub Desktop.
DenseFeatureUDF.java
/*
* Hivemall: Hive scalable Machine Learning Library
*
* Copyright (C) 2015 Makoto YUI
*
* Licensed 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.ftvec;
import hivemall.io.FeatureValue;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnegative;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.io.FloatWritable;
@Description(name = "dense_feature", value = "_FUNC_(array<string> feature_vector, int dimensions)"
+ " - Returns a dense feature in array<float>")
@UDFType(deterministic = true, stateful = false)
public final class DenseFeatureUDF extends UDF {
public List<FloatWritable> evaluate(List<String> features, @Nonnegative int dimensions) {
if(features == null) {
return null;
}
final FloatWritable[] fv = new FloatWritable[dimensions + 1];
final FeatureValue probe = new FeatureValue();
for(String ft : features) {
FeatureValue.parseFeatureAsString(ft, probe);
String f = probe.getFeature();
int i = Integer.parseInt(f);
float v = probe.getValue();
fv[i] = new FloatWritable(v);
}
return Arrays.asList(fv);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment