code stringlengths 25 201k | docstring stringlengths 19 96.2k | func_name stringlengths 0 235 | language stringclasses 1 value | repo stringlengths 8 51 | path stringlengths 11 314 | url stringlengths 62 377 | license stringclasses 7 values |
|---|---|---|---|---|---|---|---|
public static Pair<ClusterInfo,Double> closestCluster(List<ClusterInfo> clusters,
DistanceFn<double[]> distanceFn,
double[] vector) {
Preconditions.checkArgument(!clusters.isEmpty());
double closestDist = Double.POSITIVE_INFINITY;
ClusterInfo minCluster = null;
for (ClusterInfo cluster : clusters) {
double distance = distanceFn.applyAsDouble(cluster.getCenter(), vector);
if (distance < closestDist) {
closestDist = distance;
minCluster = cluster;
}
}
Preconditions.checkNotNull(minCluster);
Preconditions.checkState(!Double.isInfinite(closestDist) && !Double.isNaN(closestDist));
return new Pair<>(minCluster, closestDist);
} | @param clusters all clusters
@param distanceFn distance function between clusters
@param vector point to measure distance to
@return cluster whose center is closest to the given point | closestCluster | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | Apache-2.0 |
public static double[] featuresFromTokens(String[] data, InputSchema inputSchema) {
double[] features = new double[inputSchema.getNumPredictors()];
for (int featureIndex = 0; featureIndex < data.length; featureIndex++) {
if (inputSchema.isActive(featureIndex)) {
features[inputSchema.featureToPredictorIndex(featureIndex)] =
Double.parseDouble(data[featureIndex]);
}
}
return features;
} | @param data tokenized input
@param inputSchema input schema to apply to input
@return input parsed as numeric values | featuresFromTokens | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | Apache-2.0 |
public static void checkUniqueIDs(Collection<ClusterInfo> clusters) {
Preconditions.checkArgument(clusters.stream().map(ClusterInfo::getID).distinct().count() == clusters.size());
} | @param clusters clusters to check the IDs of
@throws IllegalArgumentException if any {@link ClusterInfo#getID()} is duplicated | checkUniqueIDs | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/kmeans/KMeansUtils.java | Apache-2.0 |
public static String getExtensionValue(PMML pmml, String name) {
return pmml.getExtensions().stream().filter(extension -> name.equals(extension.getName())).findFirst().
map(Extension::getValue).orElse(null);
} | General app tier PMML-related utility methods. | getExtensionValue | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static List<String> getExtensionContent(PMML pmml, String name) {
return pmml.getExtensions().stream().filter(extension -> name.equals(extension.getName())).findFirst().
map(extension -> {
List<?> content = extension.getContent();
Preconditions.checkArgument(content.size() <= 1);
return content.isEmpty() ?
Collections.<String>emptyList() :
Arrays.asList(TextUtils.parsePMMLDelimited(content.get(0).toString()));
}).orElse(null);
} | @param pmml PMML model to query for extensions
@param name name of extension to query
@return content of the extension, parsed as if it were a PMML {@link Array}:
space-separated values, with PMML quoting rules | getExtensionContent | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static void addExtension(PMML pmml, String key, Object value) {
pmml.addExtensions(new Extension().setName(key).setValue(value.toString()));
} | @param pmml PMML model to add extension to, with no content. It may possibly duplicate
existing extensions.
@param key extension key
@param value extension value | addExtension | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static void addExtensionContent(PMML pmml, String key, Collection<?> content) {
if (content.isEmpty()) {
return;
}
String joined = TextUtils.joinPMMLDelimited(content);
pmml.addExtensions(new Extension().setName(key).addContent(joined));
} | @param pmml PMML model to add extension to, with a single {@code String} content and no value.
The content is encoded as if they were being added to a PMML {@link Array} and are
space-separated with PMML quoting rules
@param key extension key
@param content list of values to add as a {@code String} | addExtensionContent | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static Array toArray(double... values) {
List<Double> valueList = new ArrayList<>(values.length);
for (double value : values) {
valueList.add(value);
}
String arrayValue = TextUtils.joinPMMLDelimitedNumbers(valueList);
return new Array(Array.Type.REAL, arrayValue).setN(valueList.size());
} | @param values {@code double} value to make into a PMML {@link Array}
@return PMML {@link Array} representation | toArray | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static MiningSchema buildMiningSchema(InputSchema schema) {
return buildMiningSchema(schema, null);
} | @param schema {@link InputSchema} whose information should be encoded in PMML
@return a {@link MiningSchema} representing the information contained in an
{@link InputSchema} | buildMiningSchema | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static MiningSchema buildMiningSchema(InputSchema schema, double[] importances) {
Preconditions.checkArgument(
importances == null || importances.length == schema.getNumPredictors());
List<String> featureNames = schema.getFeatureNames();
List<MiningField> miningFields = new ArrayList<>();
for (int featureIndex = 0; featureIndex < featureNames.size(); featureIndex++) {
String featureName = featureNames.get(featureIndex);
MiningField field = new MiningField(FieldName.create(featureName));
if (schema.isNumeric(featureName)) {
field.setOpType(OpType.CONTINUOUS);
field.setUsageType(MiningField.UsageType.ACTIVE);
} else if (schema.isCategorical(featureName)) {
field.setOpType(OpType.CATEGORICAL);
field.setUsageType(MiningField.UsageType.ACTIVE);
} else {
// ID, or ignored
field.setUsageType(MiningField.UsageType.SUPPLEMENTARY);
}
if (schema.hasTarget() && schema.isTarget(featureName)) {
// Override to PREDICTED
field.setUsageType(MiningField.UsageType.PREDICTED);
}
// Will be active if and only if it's a predictor
if (field.getUsageType() == MiningField.UsageType.ACTIVE && importances != null) {
int predictorIndex = schema.featureToPredictorIndex(featureIndex);
field.setImportance(importances[predictorIndex]);
}
miningFields.add(field);
}
return new MiningSchema(miningFields);
} | @param schema {@link InputSchema} whose information should be encoded in PMML
@param importances optional feature importances. May be {@code null}, or else the size
of the array must match the number of predictors in the schema, which may be
less than the total number of features.
@return a {@link MiningSchema} representing the information contained in an
{@link InputSchema} | buildMiningSchema | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static List<String> getFeatureNames(MiningSchema miningSchema) {
return miningSchema.getMiningFields().stream().map(field -> field.getName().getValue())
.collect(Collectors.toList());
} | @param miningSchema {@link MiningSchema} from a model
@return names of features in order | getFeatureNames | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/pmml/AppPMMLUtils.java | Apache-2.0 |
public static void validatePMMLVsSchema(PMML pmml, InputSchema schema) {
List<Model> models = pmml.getModels();
Preconditions.checkArgument(models.size() == 1,
"Should have exactly one model, but had %s", models.size());
Model model = models.get(0);
MiningFunction function = model.getMiningFunction();
if (schema.isClassification()) {
Preconditions.checkArgument(function == MiningFunction.CLASSIFICATION,
"Expected classification function type but got %s",
function);
} else {
Preconditions.checkArgument(function == MiningFunction.REGRESSION,
"Expected regression function type but got %s",
function);
}
DataDictionary dictionary = pmml.getDataDictionary();
Preconditions.checkArgument(
schema.getFeatureNames().equals(AppPMMLUtils.getFeatureNames(dictionary)),
"Feature names in schema don't match names in PMML");
MiningSchema miningSchema = model.getMiningSchema();
Preconditions.checkArgument(schema.getFeatureNames().equals(
AppPMMLUtils.getFeatureNames(miningSchema)));
Integer pmmlIndex = AppPMMLUtils.findTargetIndex(miningSchema);
if (schema.hasTarget()) {
int schemaIndex = schema.getTargetFeatureIndex();
Preconditions.checkArgument(
pmmlIndex != null && schemaIndex == pmmlIndex,
"Configured schema expects target at index %s, but PMML has target at index %s",
schemaIndex, pmmlIndex);
} else {
Preconditions.checkArgument(pmmlIndex == null);
}
} | Validates that the encoded PMML model received matches expected schema.
@param pmml {@link PMML} encoding of a decision forest
@param schema expected schema attributes of decision forest | validatePMMLVsSchema | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/RDFPMMLUtils.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/RDFPMMLUtils.java | Apache-2.0 |
public final int getFeatureNumber() {
return featureNumber;
} | @return number of the feature whose value the {@code Decision} operates on | getFeatureNumber | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/decision/Decision.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/decision/Decision.java | Apache-2.0 |
public String getID() {
return id;
} | @return unique ID for this node (unique within its tree) | getID | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/tree/TreeNode.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/rdf/tree/TreeNode.java | Apache-2.0 |
private static <T> BiMap<T,Integer> mapDistinctValues(Collection<? extends T> distinct) {
BiMap<T,Integer> mapping = HashBiMap.create(distinct.size());
int encoding = 0;
for (T t : distinct) {
mapping.put(t, encoding);
encoding++;
}
return mapping;
} | @param distinctValues map of categorical feature indices, to the set of distinct
values for that categorical feature. Order matters. | mapDistinctValues | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | Apache-2.0 |
public Map<String,Integer> getValueEncodingMap(int index) {
return doGetMap(index);
} | @param index feature index
@return mapping of categorical feature values to numeric encodings for the indicated
categorical feature | getValueEncodingMap | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | Apache-2.0 |
public Map<Integer,String> getEncodingValueMap(int index) {
return doGetMap(index).inverse();
} | @param index feature index
@return mapping of numeric encodings to categorical feature values for the indicated
categorical feature | getEncodingValueMap | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | Apache-2.0 |
public int getValueCount(int index) {
return doGetMap(index).size();
} | @param index feature index
@return number of distinct values of the categorical feature | getValueCount | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/CategoricalValueEncodings.java | Apache-2.0 |
public List<String> getFeatureNames() {
return featureNames;
} | @return names of features in the schema, in order | getFeatureNames | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public int getNumFeatures() {
return featureNames.size();
} | @return total number of features described in the schema | getNumFeatures | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public int getNumPredictors() {
return activeFeatures.size() - (hasTarget() ? 1 : 0);
} | @return number of features that are predictors -- not an ID, not ignored, not the target | getNumPredictors | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isID(String featureName) {
return idFeatures.contains(featureName);
} | @param featureName feature name
@return {@code true} iff feature is an ID feature | isID | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isID(int featureIndex) {
return isID(featureNames.get(featureIndex));
} | @param featureIndex feature index
@return {@code true} iff feature is an ID feature | isID | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isActive(String featureName) {
return activeFeatures.contains(featureName);
} | @param featureName feature name
@return {@code true} iff feature is active -- not an ID or ignored | isActive | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isActive(int featureIndex) {
return isActive(featureNames.get(featureIndex));
} | @param featureIndex feature index
@return {@code true} iff feature is active -- not an ID or ignored | isActive | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isNumeric(String featureName) {
return numericFeatures.contains(featureName);
} | @param featureName feature name
@return {@code true} iff feature is numeric | isNumeric | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isNumeric(int featureIndex) {
return isNumeric(featureNames.get(featureIndex));
} | @param featureIndex feature index
@return {@code true} iff feature is a numeric | isNumeric | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isCategorical(String featureName) {
return categoricalFeatures.contains(featureName);
} | @param featureName feature name
@return {@code true} iff feature is categorical | isCategorical | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isCategorical(int featureIndex) {
return isCategorical(featureNames.get(featureIndex));
} | @param featureIndex feature index
@return {@code true} iff feature is a categorical | isCategorical | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isTarget(String featureName) {
return featureName.equals(targetFeature);
} | @param featureName feature name
@return {@code true} iff the feature is the target | isTarget | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isTarget(int featureIndex) {
return targetFeatureIndex == featureIndex;
} | @param featureIndex feature index
@return {@code true} iff the feature is the target | isTarget | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public String getTargetFeature() {
Preconditions.checkState(targetFeature != null);
return targetFeature;
} | @return name of feature that is the target
@throws IllegalStateException if there is no target | getTargetFeature | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public int getTargetFeatureIndex() {
Preconditions.checkState(targetFeatureIndex >= 0);
return targetFeatureIndex;
} | @return index of feature that is the target
@throws IllegalStateException if there is no target | getTargetFeatureIndex | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean hasTarget() {
return targetFeature != null;
} | @return {@code true} iff schema defines a target feature | hasTarget | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public boolean isClassification() {
return isCategorical(getTargetFeature());
} | @return {@code true} iff the target feature is categorical
@throws IllegalStateException if there is no target | isClassification | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public int featureToPredictorIndex(int featureIndex) {
Integer predictorIndex = allToPredictorMap.get(featureIndex);
Preconditions.checkArgument(predictorIndex != null,
"No predictor for feature %s", featureIndex);
return predictorIndex;
} | @param featureIndex index (0-based) among all features
@return index (0-based) among only predictors (not ID, not ignored, not target) | featureToPredictorIndex | java | OryxProject/oryx | app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/main/java/com/cloudera/oryx/app/schema/InputSchema.java | Apache-2.0 |
public static String idToStringID(int id) {
return Character.toString((char) ('A' + Integer.remainderUnsigned(id, 26))) + id;
} | @param id nonnegative ID
@return string like "A0", "B1", ... "A26" ... | idToStringID | java | OryxProject/oryx | app/oryx-app-common/src/test/java/com/cloudera/oryx/app/als/ALSUtilsTest.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-common/src/test/java/com/cloudera/oryx/app/als/ALSUtilsTest.java | Apache-2.0 |
@Override
protected Pair<JavaRDD<String>,JavaRDD<String>> splitNewDataToTrainTest(JavaRDD<String> newData) {
// Rough approximation; assumes timestamps are fairly evenly distributed
StatCounter maxMin = newData.mapToDouble(line -> MLFunctions.TO_TIMESTAMP_FN.call(line).doubleValue()).stats();
long minTime = (long) maxMin.min();
long maxTime = (long) maxMin.max();
log.info("New data timestamp range: {} - {}", minTime, maxTime);
long approxTestTrainBoundary = (long) (maxTime - getTestFraction() * (maxTime - minTime));
log.info("Splitting at timestamp {}", approxTestTrainBoundary);
JavaRDD<String> newTrainData = newData.filter(
line -> MLFunctions.TO_TIMESTAMP_FN.call(line) < approxTestTrainBoundary);
JavaRDD<String> testData = newData.filter(
line -> MLFunctions.TO_TIMESTAMP_FN.call(line) >= approxTestTrainBoundary);
return new Pair<>(newTrainData, testData);
} | Implementation which splits based solely on time. It will return approximately
the earliest {@link #getTestFraction()} of input, ordered by timestamp, as new training
data and the rest as test data. | splitNewDataToTrainTest | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/ALSUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/ALSUpdate.java | Apache-2.0 |
private JavaRDD<Rating> aggregateScores(JavaRDD<? extends Rating> original, double epsilon) {
JavaPairRDD<Tuple2<Integer,Integer>,Double> tuples =
original.mapToPair(rating -> new Tuple2<>(new Tuple2<>(rating.user(), rating.product()), rating.rating()));
JavaPairRDD<Tuple2<Integer,Integer>,Double> aggregated;
if (implicit) {
// TODO can we avoid groupByKey? reduce, combine, fold don't seem viable since
// they don't guarantee the delete elements are properly handled
aggregated = tuples.groupByKey().mapValues(MLFunctions.SUM_WITH_NAN);
} else {
// For non-implicit, last wins.
aggregated = tuples.foldByKey(Double.NaN, (current, next) -> next);
}
JavaPairRDD<Tuple2<Integer,Integer>,Double> noNaN =
aggregated.filter(kv -> !Double.isNaN(kv._2()));
if (logStrength) {
return noNaN.map(userProductScore -> new Rating(
userProductScore._1()._1(),
userProductScore._1()._2(),
Math.log1p(userProductScore._2() / epsilon)));
} else {
return noNaN.map(userProductScore -> new Rating(
userProductScore._1()._1(),
userProductScore._1()._2(),
userProductScore._2()));
}
} | Combines {@link Rating}s with the same user/item into one, with score as the sum of
all of the scores. | aggregateScores | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/ALSUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/ALSUpdate.java | Apache-2.0 |
static double rmse(MatrixFactorizationModel mfModel, JavaRDD<Rating> testData) {
JavaPairRDD<Tuple2<Integer,Integer>,Double> testUserProductValues =
testData.mapToPair(rating -> new Tuple2<>(new Tuple2<>(rating.user(), rating.product()), rating.rating()));
@SuppressWarnings("unchecked")
RDD<Tuple2<Object,Object>> testUserProducts =
(RDD<Tuple2<Object,Object>>) (RDD<?>) testUserProductValues.keys().rdd();
JavaRDD<Rating> predictions = testData.wrapRDD(mfModel.predict(testUserProducts));
double mse = predictions.mapToPair(
rating -> new Tuple2<>(new Tuple2<>(rating.user(), rating.product()), rating.rating())
).join(testUserProductValues).values().mapToDouble(valuePrediction -> {
double diff = valuePrediction._1() - valuePrediction._2();
return diff * diff;
}).mean();
return Math.sqrt(mse);
} | Computes root mean squared error of {@link Rating#rating()} versus predicted value. | rmse | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/Evaluation.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/als/Evaluation.java | Apache-2.0 |
JavaPairRDD<Integer,ClusterMetric> fetchClusterMetrics(JavaRDD<Vector> evalData) {
return evalData.mapToPair(vector -> {
double closestDist = Double.POSITIVE_INFINITY;
int minClusterID = Integer.MIN_VALUE;
double[] vec = vector.toArray();
for (ClusterInfo cluster : clusters.values()) {
double distance = distanceFn.applyAsDouble(cluster.getCenter(), vec);
if (distance < closestDist) {
closestDist = distance;
minClusterID = cluster.getID();
}
}
Preconditions.checkState(!Double.isInfinite(closestDist) && !Double.isNaN(closestDist));
return new Tuple2<>(minClusterID, new ClusterMetric(1L, closestDist, closestDist * closestDist));
}).reduceByKey(ClusterMetric::add);
} | @param evalData points to cluster for evaluation
@return cluster IDs as keys, and metrics for each cluster like the count, sum of distances to centroid,
and sum of squared distances | fetchClusterMetrics | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/AbstractKMeansEvaluation.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/AbstractKMeansEvaluation.java | Apache-2.0 |
@Override
double evaluate(JavaRDD<Vector> evalData) {
Map<Integer,ClusterMetric> clusterMetricsByID = fetchClusterMetrics(evalData).collectAsMap();
Map<Integer,ClusterInfo> clustersByID = getClustersByID();
DistanceFn<double[]> distanceFn = getDistanceFn();
return clustersByID.entrySet().stream().mapToDouble(entryI -> {
Integer idI = entryI.getKey();
double[] centerI = entryI.getValue().getCenter();
double clusterScatter1 = clusterMetricsByID.get(idI).getMeanDist();
// this inner loop should not be set to j = (i+1) as DB Index computation is not symmetric.
// For a given cluster i, we look for a cluster j that maximizes
// the ratio of (the sum of average distances from points in cluster i to its center and
// points in cluster j to its center) to (the distance between cluster i and cluster j).
// The key here is the Maximization of the DB Index for a cluster:
// the cluster that maximizes this ratio may be j for i but not necessarily i for j
return clustersByID.entrySet().stream().mapToDouble(entryJ -> {
Integer idJ = entryJ.getKey();
if (idI.equals(idJ)) {
return 0.0;
}
double[] centerJ = entryJ.getValue().getCenter();
double clusterScatter2 = clusterMetricsByID.get(idJ).getMeanDist();
return (clusterScatter1 + clusterScatter2) / distanceFn.applyAsDouble(centerI, centerJ);
}).max().orElse(0.0);
}).average().orElse(0.0);
} | @param evalData data for evaluation
@return the Davies-Bouldin Index (http://en.wikipedia.org/wiki/Cluster_analysis#Internal_evaluation);
lower is better | evaluate | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/DaviesBouldinIndex.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/DaviesBouldinIndex.java | Apache-2.0 |
@Override
double evaluate(JavaRDD<Vector> evalData) {
// Intra-cluster distance is mean distance to centroid
double maxIntraClusterDistance =
fetchClusterMetrics(evalData).values().mapToDouble(ClusterMetric::getMeanDist).max();
// Inter-cluster distance is distance between centroids
double minInterClusterDistance = Double.POSITIVE_INFINITY;
List<ClusterInfo> clusters = new ArrayList<>(getClustersByID().values());
DistanceFn<double[]> distanceFn = getDistanceFn();
for (int i = 0; i < clusters.size(); i++) {
double[] centerI = clusters.get(i).getCenter();
// Distances are symmetric, hence d(i,j) == d(j,i)
for (int j = i + 1; j < clusters.size(); j++) {
double[] centerJ = clusters.get(j).getCenter();
minInterClusterDistance = Math.min(minInterClusterDistance, distanceFn.applyAsDouble(centerI, centerJ));
}
}
return minInterClusterDistance / maxIntraClusterDistance;
} | @param evalData data for evaluation
@return the Dunn Index of a given clustering
(https://en.wikipedia.org/wiki/Cluster_analysis#Internal_evaluation); higher is better | evaluate | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/DunnIndex.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/DunnIndex.java | Apache-2.0 |
@Override
public PMML buildModel(JavaSparkContext sparkContext,
JavaRDD<String> trainData,
List<?> hyperParameters,
Path candidatePath) {
int numClusters = (Integer) hyperParameters.get(0);
Preconditions.checkArgument(numClusters > 1);
log.info("Building KMeans Model with {} clusters", numClusters);
JavaRDD<Vector> trainingData = parsedToVectorRDD(trainData.map(MLFunctions.PARSE_FN));
KMeansModel kMeansModel = KMeans.train(trainingData.rdd(), numClusters, maxIterations, initializationStrategy);
return kMeansModelToPMML(kMeansModel, fetchClusterCountsFromModel(trainingData, kMeansModel));
} | @param sparkContext active Spark Context
@param trainData training data on which to build a model
@param hyperParameters ordered list of hyper parameter values to use in building model
@param candidatePath directory where additional model files can be written
@return a {@link PMML} representation of a model trained on the given data | buildModel | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | Apache-2.0 |
private static Map<Integer,Long> fetchClusterCountsFromModel(JavaRDD<? extends Vector> trainPointData,
KMeansModel model) {
return trainPointData.map(model::predict).countByValue();
} | @param trainPointData data to cluster
@param model trained KMeans Model
@return map of ClusterId, count of points associated with the clusterId | fetchClusterCountsFromModel | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | Apache-2.0 |
@Override
public double evaluate(JavaSparkContext sparkContext,
PMML model,
Path modelParentPath,
JavaRDD<String> testData,
JavaRDD<String> trainData) {
KMeansPMMLUtils.validatePMMLVsSchema(model, inputSchema);
JavaRDD<Vector> evalData =
parsedToVectorRDD(trainData.union(testData).map(MLFunctions.PARSE_FN));
List<ClusterInfo> clusterInfoList = KMeansPMMLUtils.read(model);
log.info("Evaluation Strategy is {}", evaluationStrategy);
double eval;
switch (evaluationStrategy) {
case DAVIES_BOULDIN:
double dbIndex = new DaviesBouldinIndex(clusterInfoList).evaluate(evalData);
log.info("Davies-Bouldin index: {}", dbIndex);
eval = -dbIndex;
break;
case DUNN:
double dunnIndex = new DunnIndex(clusterInfoList).evaluate(evalData);
log.info("Dunn index: {}", dunnIndex);
eval = dunnIndex;
break;
case SILHOUETTE:
double silhouette = new SilhouetteCoefficient(clusterInfoList).evaluate(evalData);
log.info("Silhouette Coefficient: {}", silhouette);
eval = silhouette;
break;
case SSE :
double sse = new SumSquaredError(clusterInfoList).evaluate(evalData);
log.info("Sum squared error: {}", sse);
eval = -sse;
break;
default:
throw new IllegalArgumentException("Unknown evaluation strategy " + evaluationStrategy);
}
return eval;
} | @param sparkContext active Spark Context
@param model model to evaluate
@param modelParentPath directory containing model files, if applicable
@param testData data on which to test the model performance
@return an evaluation of the model on the test data. Higher should mean "better" | evaluate | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/kmeans/KMeansUpdate.java | Apache-2.0 |
private static List<IntLongHashMap> treeNodeExampleCounts(JavaRDD<? extends LabeledPoint> trainPointData,
RandomForestModel model) {
return trainPointData.mapPartitions(data -> {
DecisionTreeModel[] trees = model.trees();
List<IntLongHashMap> treeNodeIDCounts = IntStream.range(0, trees.length).
mapToObj(i -> new IntLongHashMap()).collect(Collectors.toList());
data.forEachRemaining(datum -> {
double[] featureVector = datum.features().toArray();
for (int i = 0; i < trees.length; i++) {
DecisionTreeModel tree = trees[i];
IntLongHashMap nodeIDCount = treeNodeIDCounts.get(i);
org.apache.spark.mllib.tree.model.Node node = tree.topNode();
// This logic cloned from Node.predict:
while (!node.isLeaf()) {
// Count node ID
nodeIDCount.addToValue(node.id(), 1);
Split split = node.split().get();
int featureIndex = split.feature();
node = nextNode(featureVector, node, split, featureIndex);
}
nodeIDCount.addToValue(node.id(), 1);
}
});
return Collections.singleton(treeNodeIDCounts).iterator();
}
).reduce((a, b) -> {
Preconditions.checkArgument(a.size() == b.size());
for (int i = 0; i < a.size(); i++) {
merge(a.get(i), b.get(i));
}
return a;
});
} | @param trainPointData data to run down trees
@param model random decision forest model to count on
@return maps of node IDs to the count of training examples that reached that node, one
per tree in the model
@see #predictorExampleCounts(JavaRDD,RandomForestModel) | treeNodeExampleCounts | java | OryxProject/oryx | app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/rdf/RDFUpdate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/main/java/com/cloudera/oryx/app/batch/mllib/rdf/RDFUpdate.java | Apache-2.0 |
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
int user = random.nextInt(numUsers);
int randProduct = random.nextInt(numProducts);
// Want product === user mod features
int product = ((user % features) + (randProduct / features) * features) % numProducts;
String datum = ALSUtilsTest.idToStringID(user) + ',' + ALSUtilsTest.idToStringID(product) +
",1," + System.currentTimeMillis();
return new Pair<>(Integer.toString(id), datum);
} | Creates random data where products associated to users fall neatly into
a given number of distinct categories, which is most naturally modeled
by a factorization with that same number of features.
User and product IDs are actually non-numeric, and generated as "A0", "B1", ... , "A26", etc. | generate | java | OryxProject/oryx | app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/als/FeaturesALSDataGenerator.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/als/FeaturesALSDataGenerator.java | Apache-2.0 |
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
String userString = ALSUtilsTest.idToStringID(random.nextInt(numUsers));
String itemString = ALSUtilsTest.idToStringID(random.nextInt(numProducts));
int rating = random.nextInt(maxRating - minRating + 1) + minRating;
String datum = userString + ',' + itemString + ',' + rating + ',' + System.currentTimeMillis();
return new Pair<>(Integer.toString(id), datum);
} | Generates random "user,product,rating,timestamp" data. The user is an integer chosen from
[0,numUsers) uniformly at random, and likewise for the product, from [0,numProducts).
User and product IDs are actually non-numeric, and generated as "A0", "B1", ... , "A26", etc.
Rating is an integer chosen from [minRating,maxRating]. Timestamp is the current time. | generate | java | OryxProject/oryx | app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/als/RandomALSDataGenerator.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/als/RandomALSDataGenerator.java | Apache-2.0 |
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
List<String> elements = new ArrayList<>(n + 2);
elements.add(Integer.toString(id));
boolean positive = true;
for (int i = 0; i < n; i++) {
double d = random.nextDouble();
if (d < 0.5) {
positive = false;
}
elements.add(Double.toString(d));
}
elements.add(Boolean.toString(positive));
return new Pair<>(Integer.toString(id), TextUtils.joinDelimited(elements, ','));
} | Generations n+2 dimensional data, where the first column is an ID, the next n
columns are continuous values in [0,1] and the last is always "true" or "false".
The data is generated such that the positive class "true" only occurs when all
dimensions are at least 0.5. The resulting data is returned as a CSV string. | generate | java | OryxProject/oryx | app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/rdf/RandomCategoricalRDFDataGenerator.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/rdf/RandomCategoricalRDFDataGenerator.java | Apache-2.0 |
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
List<String> elements = new ArrayList<>(n + 2);
elements.add(Integer.toString(id));
int count = 0;
for (int i = 0; i < n; i++) {
boolean positive = random.nextBoolean();
elements.add(positive ? "A" : "B");
if (positive) {
count++;
}
}
elements.add(Integer.toString(count));
return new Pair<>(Integer.toString(id), TextUtils.joinDelimited(elements, ','));
} | Generations n+2 dimensional data, where the first column is an ID, the next n
columns are categorical values in [A,B] and the last is equal to the number of features
that are A. The resulting data is returned as a CSV string. | generate | java | OryxProject/oryx | app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/rdf/RandomNumericRDFDataGenerator.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-mllib/src/test/java/com/cloudera/oryx/app/batch/mllib/rdf/RandomNumericRDFDataGenerator.java | Apache-2.0 |
@GET
@Path("/allIDs")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public Collection<String> get() throws OryxServingException {
return getALSServingModel().getAllItemIDs();
} | <p>Responds to a GET request to {@code /item/allIDs}.</p>
<p>CSV output consists of one ID per line. JSON output is an array of item IDs.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/AllItemIDs.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/AllItemIDs.java | Apache-2.0 |
@GET
@Path("/allIDs")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public Collection<String> get() throws OryxServingException {
return getALSServingModel().getAllUserIDs();
} | <p>Responds to a GET request to {@code /user/allIDs}.</p>
<p>CSV output consists of one ID per line. JSON output is an array of user IDs.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/AllUserIDs.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/AllUserIDs.java | Apache-2.0 |
@GET
@Path("{userID}/{itemID}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("userID") String userID,
@PathParam("itemID") String itemID,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset) throws OryxServingException {
check(howMany > 0, "howMany must be positive");
check(offset >= 0, "offset must be non-negative");
ALSServingModel model = getALSServingModel();
float[] itemVector = model.getItemVector(itemID);
checkExists(itemVector != null, itemID);
List<Pair<String,float[]>> knownItemVectors = model.getKnownItemVectorsForUser(userID);
if (knownItemVectors == null || knownItemVectors.isEmpty()) {
return Collections.emptyList();
}
double itemVectorNorm = VectorMath.norm(itemVector);
Stream<Pair<String,Double>> idSimilarities = knownItemVectors.stream().map(itemIDVector -> {
float[] otherItemVector = itemIDVector.getSecond();
double cosineSimilarity = VectorMath.cosineSimilarity(otherItemVector, itemVector, itemVectorNorm);
return new Pair<>(itemIDVector.getFirst(), cosineSimilarity);
});
return toIDValueResponse(idSimilarities.sorted(Pairs.orderBySecond(Pairs.SortOrder.DESCENDING)),
howMany, offset);
} | <p>Responds to a GET request to {@code /because/[userID]/[itemID](?howMany=n)(&offset=o)}.</p>
<p>Results are items that the user has interacted with that best explain why a given
item was recommended. Outputs contain item and score pairs, where the score is an opaque
value where higher values mean more relevant to recommendation.</p>
<p>If the user is not known to the model, a
{@link javax.ws.rs.core.Response.Status#NOT_FOUND} response is generated.
If the user has no known items associated, the response has no elements.</p>
<p>{@code howMany} and {@code offset} behavior, and output, are as in {@link Recommend}.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Because.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Because.java | Apache-2.0 |
@GET
@Path("{userID}/{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<Double> get(@PathParam("userID") String userID,
@PathParam("itemID") List<PathSegment> pathSegmentsList)
throws OryxServingException {
ALSServingModel model = getALSServingModel();
float[] userFeatures = model.getUserVector(userID);
checkExists(userFeatures != null, userID);
return pathSegmentsList.stream().map(pathSegment -> {
float[] itemFeatures = model.getItemVector(pathSegment.getPath());
if (itemFeatures == null) {
return 0.0;
} else {
double value = VectorMath.dot(itemFeatures, userFeatures);
Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad estimate");
return value;
}
}).collect(Collectors.toList());
} | <p>Responds to a GET request to {@code /estimate/[userID]/[itemID]}.</p>
<p>The results are opaque values which estimate the strength of interaction between a user
and item. Higher values mean stronger interaction.</p>
<p>This REST endpoint can also compute several estimates at once. Send a GET request to
{@code /estimate/[userID]/[itemID1](/[itemID2]/...)}.</p>
<p>If the user is not known to the model, a {@link javax.ws.rs.core.Response.Status#NOT_FOUND}
response is generated. If any item is not known, then that entry in the response will be 0.</p>
<p>The output are estimates, in the same order as the item IDs. For default CSV output,
each line contains one estimate. For JSON output, the result is an array of estimates.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Estimate.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Estimate.java | Apache-2.0 |
@GET
@Path("{toItemID}/{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public Double get(
@PathParam("toItemID") String toItemID,
@PathParam("itemID") List<PathSegment> pathSegments) throws OryxServingException {
ALSServingModel model = getALSServingModel();
float[] toItemVector = model.getItemVector(toItemID);
checkExists(toItemVector != null, toItemID);
float[] anonymousUserFeatures = buildTemporaryUserVector(model, parsePathSegments(pathSegments), null);
return anonymousUserFeatures == null ? 0.0 : VectorMath.dot(anonymousUserFeatures, toItemVector);
} | <p>Responds to a GET request to
{@code /estimateForAnonymous/[toItemID]/[itemID1(=value1)](/[itemID2(=value2)]/...)}.
That is, 1 or more item IDs are supplied, which may each optionally correspond to
a value or else default to 1.</p>
<p>Unknown item IDs are ignored.</p>
<p>Outputs the result of the method call as a value on one line.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/EstimateForAnonymous.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/EstimateForAnonymous.java | Apache-2.0 |
@GET
@Path("{userID}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public Collection<String> get(@PathParam("userID") String userID) throws OryxServingException {
return getALSServingModel().getKnownItems(userID);
} | <p>Responds to a GET request to {@code /knownItems/[userID]}.</p>
<p>CSV output consists of one ID per line. JSON output is an array of item IDs.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/KnownItems.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/KnownItems.java | Apache-2.0 |
@GET
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDCount> get(@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@QueryParam("rescorerParams") List<String> rescorerParams)
throws OryxServingException {
ALSServingModel model = getALSServingModel();
RescorerProvider rescorerProvider = model.getRescorerProvider();
Rescorer rescorer = null;
if (rescorerProvider != null) {
rescorer = rescorerProvider.getMostActiveUsersRescorer(rescorerParams);
}
return MostPopularItems.mapTopCountsToIDCounts(
model.getUserCounts(), howMany, offset, rescorer);
} | <p>Responds to a GET request to
{@code /mostActiveUsers(?howMany=n)(&offset=o)(&rescorerParams=...)}</p>
<p>Results are users that have interacted with the most items, as user and count pairs.</p>
<p>{@code howMany} and {@code offset} behavior are as in {@link Recommend}. Output
is also the same, except that user IDs are returned with integer counts rather than
scores.</p>
@see MostPopularItems | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/MostActiveUsers.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/MostActiveUsers.java | Apache-2.0 |
@GET
@Path("{userID}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("userID") String userID,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset) throws OryxServingException {
check(howMany > 0, "howMany must be positive");
check(offset >= 0, "offset must be nonnegative");
ALSServingModel model = getALSServingModel();
float[] userVector = model.getUserVector(userID);
checkExists(userVector != null, userID);
List<Pair<String,float[]>> knownItemVectors = model.getKnownItemVectorsForUser(userID);
if (knownItemVectors == null || knownItemVectors.isEmpty()) {
return Collections.emptyList();
}
Stream<Pair<String,Double>> idDots = knownItemVectors.stream().map(itemIDVector ->
new Pair<>(itemIDVector.getFirst(), VectorMath.dot(userVector, itemIDVector.getSecond())));
return toIDValueResponse(idDots.sorted(Pairs.orderBySecond(Pairs.SortOrder.ASCENDING)),
howMany, offset);
} | <p>Responds to a GET request to {@code /mostSurprising/[userID](?howMany=n)(?offset=o)}.
<p>This is like an anti-{@code recommend} method, where the results are taken from among
the items that the user has already interacted with, and the results are items that
seem least-likely to be interacted with according to the model.
Outputs contain item and score pairs, where the score is an opaque
value where higher values mean more surprising.</p>
<p>If the user is not known to the model, a
{@link javax.ws.rs.core.Response.Status#NOT_FOUND} response is generated.
If the user has no known items associated, the response has no elements.</p>
<p>{@code howMany} and {@code offset} behavior, and output, are as in {@link Recommend}.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/MostSurprising.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/MostSurprising.java | Apache-2.0 |
@GET
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<String> get() throws OryxServingException {
ALSServingModel model = getALSServingModel();
int features = model.getFeatures();
List<String> items = new ArrayList<>(features);
float[] unitVector = new float[features];
for (int i = 0; i < features; i++) {
unitVector[i] = 1.0f;
Stream<Pair<String,Double>> topIDDot = model.topN(new DotsFunction(unitVector), null, 1, null);
items.add(topIDDot.findFirst().map(Pair::getFirst).orElse(null));
unitVector[i] = 0.0f; // reset
}
return items;
} | <p>Responds to a GET request to {@code /popularRepresentativeItems}.</p>
<p>The result is a list of items that is in some way representative of the range of
items in the model. That is, the items will tend to be different from each other,
and popular. Specifically, it is "recommending" one item to each of the latent
features in the model.</p>
<p>Output is one item ID per line, or in the case of JSON output, an array of IDs.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/PopularRepresentativeItems.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/PopularRepresentativeItems.java | Apache-2.0 |
@GET
@Path("{userID}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("userID") String userID,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("false") @QueryParam("considerKnownItems") boolean considerKnownItems,
@QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException {
int howManyOffset = checkHowManyOffset(howMany, offset);
ALSServingModel model = getALSServingModel();
float[] userVector = model.getUserVector(userID);
checkExists(userVector != null, userID);
Predicate<String> allowedFn = null;
if (!considerKnownItems) {
Collection<String> knownItems = model.getKnownItems(userID);
if (!knownItems.isEmpty()) {
allowedFn = v -> !knownItems.contains(v);
}
}
ToDoubleObjDoubleBiFunction<String> rescoreFn = null;
RescorerProvider rescorerProvider = getALSServingModel().getRescorerProvider();
if (rescorerProvider != null) {
Rescorer rescorer = rescorerProvider.getRecommendRescorer(Collections.singletonList(userID),
rescorerParams);
if (rescorer != null) {
Predicate<String> rescorerPredicate = id -> !rescorer.isFiltered(id);
allowedFn = allowedFn == null ? rescorerPredicate : allowedFn.and(rescorerPredicate);
rescoreFn = rescorer::rescore;
}
}
Stream<Pair<String,Double>> topIDDots = model.topN(
new DotsFunction(userVector),
rescoreFn,
howManyOffset,
allowedFn);
return toIDValueResponse(topIDDots, howMany, offset);
} | <p>Responds to a GET request to
{@code /recommend/[userID](?howMany=n)(&offset=o)(&considerKnownItems=c)(&rescorerParams=...)}
</p>
<p>Results are recommended items for the user, along with a score.
Outputs contain item and score pairs, where the score is an opaque
value where higher values mean a better recommendation.</p>
<p>{@code offset} is an offset into the entire list of results; {@code howMany} is the desired
number of results to return from there. For example, {@code offset=30} and {@code howMany=5}
will cause the implementation to retrieve 35 results internally and output the last 5.
If {@code howMany} is not specified, defaults to 10. {@code offset} defaults to 0.</p>
<p>{@code considerKnownItems} causes items that the user has interacted with to be
eligible to be returned as recommendations. It defaults to {@code false}, meaning that these
previously interacted-with items are not returned in recommendations.</p>
<p>If the user is not known to the model, a {@link javax.ws.rs.core.Response.Status#NOT_FOUND}
response is generated.</p>
<p>Default output is CSV format, containing {@code id,value} per line.
JSON format can also be selected by an appropriate {@code Accept} header. It returns
an array of recommendations, each of which has an "id" and "value" entry, like
[{"id":"I2","value":0.141348009071816},...]</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Recommend.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Recommend.java | Apache-2.0 |
@GET
@Path("{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("itemID") List<PathSegment> pathSegments,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException {
check(!pathSegments.isEmpty(), "Need at least 1 item to make recommendations");
int howManyOffset = checkHowManyOffset(howMany, offset);
ALSServingModel model = getALSServingModel();
List<Pair<String,Double>> parsedPathSegments = EstimateForAnonymous.parsePathSegments(pathSegments);
float[] anonymousUserFeatures = EstimateForAnonymous.buildTemporaryUserVector(model, parsedPathSegments, null);
check(anonymousUserFeatures != null, pathSegments.toString());
List<String> knownItems = parsedPathSegments.stream().map(Pair::getFirst).collect(Collectors.toList());
Collection<String> knownItemsSet = new HashSet<>(knownItems);
Predicate<String> allowedFn = v -> !knownItemsSet.contains(v);
ToDoubleObjDoubleBiFunction<String> rescoreFn = null;
RescorerProvider rescorerProvider = getALSServingModel().getRescorerProvider();
if (rescorerProvider != null) {
Rescorer rescorer = rescorerProvider.getRecommendToAnonymousRescorer(knownItems,
rescorerParams);
if (rescorer != null) {
allowedFn = allowedFn.and(id -> !rescorer.isFiltered(id));
rescoreFn = rescorer::rescore;
}
}
Stream<Pair<String,Double>> topIDDots = model.topN(
new DotsFunction(anonymousUserFeatures),
rescoreFn,
howManyOffset,
allowedFn);
return toIDValueResponse(topIDDots, howMany, offset);
} | <p>Responds to a GET request to
{@code /recommendToAnonymous/[itemID1(=value1)](/[itemID2(=value2)]/...)(?howMany=n)(&offset=o)(&rescorerParams=...)}
</p>
<p>Results are recommended items for an "anonymous" user, along with a score. The user is
defined by a set of items and optional interaction strengths, as in
{@link EstimateForAnonymous}.
Outputs contain item and score pairs, where the score is an opaque
value where higher values mean a better recommendation.</p>
<p>{@code howMany}, {@code considerKnownItems} and {@code offset} behavior, and output, are as in
{@link Recommend}.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendToAnonymous.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendToAnonymous.java | Apache-2.0 |
@GET
@Path("{userID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("userID") List<PathSegment> pathSegmentsList,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("false") @QueryParam("considerKnownItems") boolean considerKnownItems,
@QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException {
check(!pathSegmentsList.isEmpty(), "Need at least 1 user");
int howManyOffset = checkHowManyOffset(howMany, offset);
ALSServingModel alsServingModel = getALSServingModel();
float[][] userFeaturesVectors = new float[pathSegmentsList.size()][];
Collection<String> userKnownItems = new HashSet<>();
List<String> userIDs = new ArrayList<>(userFeaturesVectors.length);
for (int i = 0; i < userFeaturesVectors.length; i++) {
String userID = pathSegmentsList.get(i).getPath();
userIDs.add(userID);
float[] userFeatureVector = alsServingModel.getUserVector(userID);
checkExists(userFeatureVector != null, userID);
userFeaturesVectors[i] = userFeatureVector;
if (!considerKnownItems) {
userKnownItems.addAll(alsServingModel.getKnownItems(userID));
}
}
Predicate<String> allowedFn = null;
if (!userKnownItems.isEmpty()) {
allowedFn = v -> !userKnownItems.contains(v);
}
ToDoubleObjDoubleBiFunction<String> rescoreFn = null;
RescorerProvider rescorerProvider = getALSServingModel().getRescorerProvider();
if (rescorerProvider != null) {
Rescorer rescorer = rescorerProvider.getRecommendRescorer(userIDs, rescorerParams);
if (rescorer != null) {
Predicate<String> rescorerPredicate = id -> !rescorer.isFiltered(id);
allowedFn = allowedFn == null ? rescorerPredicate : allowedFn.and(rescorerPredicate);
rescoreFn = rescorer::rescore;
}
}
Stream<Pair<String,Double>> topIDDots = alsServingModel.topN(
new DotsFunction(userFeaturesVectors),
rescoreFn,
howManyOffset,
allowedFn);
return toIDValueResponse(topIDDots, howMany, offset);
} | <p>Responds to a GET request to
{@code /recommendToMany/[userID1](/[userID2]/...)(?howMany=n)(&offset=o)(&considerKnownItems=c)(&rescorerParams=...)}
</p>
<p>Results are recommended items for the user, along with a score.
Outputs contain item and score pairs, where the score is an opaque
value where higher values mean a better recommendation.</p>
<p>{@code howMany}, {@code considerKnownItems} and {@code offset} behavior, and output,
are as in {@link Recommend}.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendToMany.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendToMany.java | Apache-2.0 |
@GET
@Path("{userID}/{itemID : .*}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("userID") String userID,
@PathParam("itemID") List<PathSegment> pathSegments,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("false") @QueryParam("considerKnownItems") boolean considerKnownItems,
@QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException {
int howManyOffset = checkHowManyOffset(howMany, offset);
ALSServingModel model = getALSServingModel();
List<Pair<String,Double>> parsedPathSegments = EstimateForAnonymous.parsePathSegments(pathSegments);
float[] userVector = model.getUserVector(userID);
checkExists(userVector != null, userID);
float[] tempUserVector = EstimateForAnonymous.buildTemporaryUserVector(model, parsedPathSegments, userVector);
Set<String> knownItems = parsedPathSegments.stream().map(Pair::getFirst).collect(Collectors.toSet());
if (!considerKnownItems) {
knownItems.addAll(model.getKnownItems(userID));
}
Predicate<String> allowedFn = v -> !knownItems.contains(v);
ToDoubleObjDoubleBiFunction<String> rescoreFn = null;
RescorerProvider rescorerProvider = getALSServingModel().getRescorerProvider();
if (rescorerProvider != null) {
Rescorer rescorer = rescorerProvider.getRecommendRescorer(Collections.singletonList(userID),
rescorerParams);
if (rescorer != null) {
allowedFn = allowedFn.and(id -> !rescorer.isFiltered(id));
rescoreFn = rescorer::rescore;
}
}
Stream<Pair<String,Double>> topIDDots = model.topN(
new DotsFunction(tempUserVector),
rescoreFn,
howManyOffset,
allowedFn);
return toIDValueResponse(topIDDots, howMany, offset);
} | <p>Responds to a GET request to
{@code /recommendWithContext/[userID]/([itemID1(=value1)]/...)
(?howMany=n)(&offset=o)(&considerKnownItems=c)(&rescorerParams=...)}
</p>
<p>This endpoint operates like a combination of {@code /recommend} and {@code /recommendToAnonymous}.
It creates recommendations for a user, but modifies the recommendation as if the user also
interacted with a given set of items. This creates no model updates. It's useful for recommending
in the context of some possibly temporary interactions, like products in a basket.</p>
<p>{@code howMany}, {@code considerKnownItems} and {@code offset} behavior, and output, are as in
{@link Recommend}.</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendWithContext.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/RecommendWithContext.java | Apache-2.0 |
@GET
@Path("{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(
@PathParam("itemID") List<PathSegment> pathSegmentsList,
@DefaultValue("10") @QueryParam("howMany") int howMany,
@DefaultValue("0") @QueryParam("offset") int offset,
@QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException {
check(!pathSegmentsList.isEmpty(), "Need at least 1 item to determine similarity");
int howManyOffset = checkHowManyOffset(howMany, offset);
ALSServingModel alsServingModel = getALSServingModel();
float[][] itemFeatureVectors = new float[pathSegmentsList.size()][];
Collection<String> knownItems = new HashSet<>();
for (int i = 0; i < itemFeatureVectors.length; i++) {
String itemID = pathSegmentsList.get(i).getPath();
float[] itemVector = alsServingModel.getItemVector(itemID);
checkExists(itemVector != null, itemID);
itemFeatureVectors[i] = itemVector;
knownItems.add(itemID);
}
Predicate<String> allowedFn = v -> !knownItems.contains(v);
ToDoubleObjDoubleBiFunction<String> rescoreFn = null;
RescorerProvider rescorerProvider = getALSServingModel().getRescorerProvider();
if (rescorerProvider != null) {
Rescorer rescorer = rescorerProvider.getMostSimilarItemsRescorer(rescorerParams);
if (rescorer != null) {
allowedFn = allowedFn.and(id -> !rescorer.isFiltered(id));
rescoreFn = rescorer::rescore;
}
}
Stream<Pair<String,Double>> topIDCosines = alsServingModel.topN(
new CosineAverageFunction(itemFeatureVectors),
rescoreFn,
howManyOffset,
allowedFn);
return toIDValueResponse(topIDCosines, howMany, offset);
} | <p>Responds to a GET request to
{@code /similarity/[itemID1](/[itemID2]/...)(?howMany=n)(&offset=o)(&rescorerParams=...)}
</p>
<p>Results are items that are most similar to a given item.
Outputs contain item and score pairs, where the score is an opaque
value where higher values mean more relevant to recommendation.</p>
<p>{@code howMany} and {@code offset} behavior, and output, are as in {@link Recommend}.</p>
<p>Default output is CSV format, containing {@code id,value} per line.
JSON format can also be selected by an appropriate {@code Accept} header. It returns
an array of similarities, each of which has an "id" and "value" entry, like
[{"id":"I2","value":0.141348009071816},...]</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Similarity.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/Similarity.java | Apache-2.0 |
@GET
@Path("{toItemID}/{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<Double> get(
@PathParam("toItemID") String toItemID,
@PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException {
ALSServingModel alsServingModel = getALSServingModel();
float[] toItemFeatures = alsServingModel.getItemVector(toItemID);
checkExists(toItemFeatures != null, toItemID);
double toItemFeaturesNorm = VectorMath.norm(toItemFeatures);
return pathSegmentsList.stream().map(item -> {
float[] itemFeatures = alsServingModel.getItemVector(item.getPath());
if (itemFeatures == null) {
return 0.0;
} else {
double value = VectorMath.cosineSimilarity(itemFeatures, toItemFeatures, toItemFeaturesNorm);
Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad similarity");
return value;
}
}).collect(Collectors.toList());
} | <p>Responds to a GET request to {@code /similarityToItem/[toItemID]/[itemID1](/[itemID2]/...)}.
<p>This computes cosine similarity between an item and one or more other items.</p>
<p>The output are similarities, in the same order as the item IDs, with format
as in {@link Estimate}</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/SimilarityToItem.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/SimilarityToItem.java | Apache-2.0 |
public Map<String,Integer> getUserCounts() {
Map<String,Integer> counts;
try (AutoLock al = knownItemsLock.autoReadLock()) {
counts = new HashMap<>(knownItems.size());
knownItems.forEach((userID, ids) -> {
int numItems;
synchronized (ids) {
numItems = ids.size();
}
counts.put(userID, numItems);
});
}
return counts;
} | @return mapping of user IDs to count of items the user has interacted with | getUserCounts | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
public Collection<String> getAllUserIDs() {
Collection<String> allUserIDs = UnifiedSet.newSet(X.size());
X.addAllIDsTo(allUserIDs);
return allUserIDs;
} | @return all user IDs in the model | getAllUserIDs | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
public Collection<String> getAllItemIDs() {
Collection<String> allItemIDs = UnifiedSet.newSet(Y.size());
Y.addAllIDsTo(allItemIDs);
return allItemIDs;
} | @return all item IDs in the model | getAllItemIDs | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
public Solver getYTYSolver() {
return cachedYTYSolver.get(true);
} | @return a {@link Solver} for use in solving systems involving YT*Y | getYTYSolver | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
void retainRecentAndUserIDs(Collection<String> users) {
X.retainRecentAndIDs(users);
try (AutoLock al = expectedUserIDsLock.autoWriteLock()) {
expectedUserIDs.clear();
expectedUserIDs.addAll(users);
X.removeAllIDsFrom(expectedUserIDs);
}
} | Retains only users that are expected to appear
in the upcoming model updates, or, that have arrived recently. This also clears the
recent known users data structure.
@param users users that should be retained, which are coming in the new model updates | retainRecentAndUserIDs | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
void retainRecentAndItemIDs(Collection<String> items) {
Y.retainRecentAndIDs(items);
try (AutoLock al = expectedItemIDsLock.autoWriteLock()) {
expectedItemIDs.clear();
expectedItemIDs.addAll(items);
Y.removeAllIDsFrom(expectedItemIDs);
}
} | Retains only items that are expected to appear
in the upcoming model updates, or, that have arrived recently. This also clears the
recent known items data structure.
@param items items that should be retained, which are coming in the new model updates | retainRecentAndItemIDs | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
void retainRecentAndKnownItems(Collection<String> users, Collection<String> items) {
// Keep all users in the new model, or, that have been added since last model
MutableSet<String> recentUserIDs = UnifiedSet.newSet();
X.addAllRecentTo(recentUserIDs);
try (AutoLock al = knownItemsLock.autoWriteLock()) {
knownItems.keySet().removeIf(key -> !users.contains(key) && !recentUserIDs.contains(key));
}
// This will be easier to quickly copy the whole (smallish) set rather than
// deal with locks below
MutableSet<String> allRecentKnownItems = UnifiedSet.newSet();
Y.addAllRecentTo(allRecentKnownItems);
Predicate<String> notKeptOrRecent = value -> !items.contains(value) && !allRecentKnownItems.contains(value);
try (AutoLock al = knownItemsLock.autoReadLock()) {
knownItems.values().forEach(knownItemsForUser -> {
synchronized (knownItemsForUser) {
knownItemsForUser.removeIf(notKeptOrRecent);
}
});
}
} | Like {@link #retainRecentAndUserIDs(Collection)} and {@link #retainRecentAndItemIDs(Collection)}
but affects the known-items data structure.
@param users users that should be retained, which are coming in the new model updates
@param items items that should be retained, which are coming in the new model updates | retainRecentAndKnownItems | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
public int getNumUsers() {
return X.size();
} | @return number of users in the model | getNumUsers | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/ALSServingModel.java | Apache-2.0 |
int getIndexFor(float[] vector) {
int index = 0;
for (int i = 0; i < hashVectors.length; i++) {
if (VectorMath.dot(hashVectors[i], vector) > 0.0) {
index |= 1 << i;
}
}
return index;
} | @param vector vector to hash
@return index of partition into which it hashes | getIndexFor | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/LocalitySensitiveHash.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/als/model/LocalitySensitiveHash.java | Apache-2.0 |
@GET
@Path("{datum}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<IDValue> get(@PathParam("datum") String datum) throws OryxServingException {
check(datum != null && !datum.isEmpty(), "Missing input data");
RDFServingModel model = (RDFServingModel) getServingModel();
InputSchema inputSchema = model.getInputSchema();
check(inputSchema.isClassification(), "Only applicable for classification");
Prediction prediction = model.makePrediction(TextUtils.parseDelimited(datum, ','));
double[] probabilities = ((CategoricalPrediction) prediction).getCategoryProbabilities();
int targetIndex = inputSchema.getTargetFeatureIndex();
CategoricalValueEncodings valueEncodings = model.getEncodings();
Map<Integer,String> targetEncodingName = valueEncodings.getEncodingValueMap(targetIndex);
List<IDValue> result = new ArrayList<>(probabilities.length);
for (int i = 0; i < probabilities.length; i++) {
result.add(new IDValue(targetEncodingName.get(i), probabilities[i]));
}
return result;
} | <p>Responds to a GET request to {@code /classificationDistribution/[datum]}.
Like {@link com.cloudera.oryx.app.serving.classreg.Predict} but this
returns not just the most probable category,
but all categories and their associated probability. It is not defined for
regression problems and returns an error.</p>
<p>Default output is CSV format, containing {@code category,probability} per line.
JSON format can also be selected by an appropriate {@code Accept} header. It returns
an array of probabilities, each of which has an "id" and "value" entry, like
[{"id":"I2","value":0.141348009071816},...]</p> | get | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/rdf/ClassificationDistribution.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/rdf/ClassificationDistribution.java | Apache-2.0 |
@Override
protected String getConsoleResource() {
return "rdf/rdf.html.fragment";
} | Random decision forest app Serving Layer console. | getConsoleResource | java | OryxProject/oryx | app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/rdf/Console.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/main/java/com/cloudera/oryx/app/serving/rdf/Console.java | Apache-2.0 |
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]");
return;
}
String[] hostStrings = COMMA.split(args[0]);
Preconditions.checkArgument(hostStrings.length >= 1);
int requestIntervalMS = Integer.parseInt(args[1]);
Preconditions.checkArgument(requestIntervalMS >= 0);
int numThreads = Integer.parseInt(args[2]);
Preconditions.checkArgument(numThreads >= 1);
String[] otherArgs = new String[args.length - 3];
System.arraycopy(args, 3, otherArgs, 0, otherArgs.length);
List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList());
int perClientRequestIntervalMS = numThreads * requestIntervalMS;
Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints());
AtomicLong requestCount = new AtomicLong();
AtomicLong serverErrorCount = new AtomicLong();
AtomicLong clientErrorCount = new AtomicLong();
AtomicLong exceptionCount = new AtomicLong();
long start = System.nanoTime();
ExecUtils.doInParallel(numThreads, numThreads, true, i -> {
RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
ExponentialDistribution msBetweenRequests;
if (perClientRequestIntervalMS > 0) {
msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS);
} else {
msBetweenRequests = null;
}
ClientConfig clientConfig = new ClientConfig();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(numThreads);
connectionManager.setDefaultMaxPerRoute(numThreads);
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
clientConfig.connectorProvider(new ApacheConnectorProvider());
Client client = ClientBuilder.newClient(clientConfig);
try {
while (true) {
try {
WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size())));
Endpoint endpoint = alsEndpoints.chooseEndpoint(random);
Invocation invocation = endpoint.makeInvocation(target, otherArgs, random);
int statusCode;
long startTime = System.nanoTime();
try (Response response = invocation.invoke()) {
response.readEntity(String.class);
statusCode = response.getStatusInfo().getStatusCode();
}
long elapsedNanos = System.nanoTime() - startTime;
if (statusCode >= 400) {
if (statusCode >= 500) {
serverErrorCount.incrementAndGet();
} else {
clientErrorCount.incrementAndGet();
}
}
endpoint.recordTiming(elapsedNanos);
if (requestCount.incrementAndGet() % 10000 == 0) {
long elapsedOverallNanos = System.nanoTime() - start;
log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)",
Math.round(elapsedOverallNanos / 1_000_000.0),
requestCount.get(),
clientErrorCount.get(),
serverErrorCount.get(),
exceptionCount.get());
for (Endpoint e : alsEndpoints.getEndpoints()) {
log.info("{}", e);
}
}
if (msBetweenRequests != null) {
long elapsedMS = Math.round(elapsedNanos / 1_000_000.0);
int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample());
if (elapsedMS < desiredElapsedMS) {
Thread.sleep(desiredElapsedMS - elapsedMS);
}
}
} catch (Exception e) {
exceptionCount.incrementAndGet();
log.warn("{}", e.getMessage());
}
}
} finally {
client.close();
}
});
} | Simple utility class for sending traffic to an Oryx cluster for an extended period of time.
Required args:
<ol>
<li>{@code hosts} comma-separated distinct host:port pairs to send HTTP requests to</li>
<li>{@code requestIntervalMS} average delay between requests in MS</li>
<li>{@code threads} number of concurrent requests</li>
</ol>
These can be followed by more args that are passed to subclasses of {@link Endpoint}. | main | java | OryxProject/oryx | app/oryx-app-serving/src/test/java/com/cloudera/oryx/app/traffic/TrafficUtil.java | https://github.com/OryxProject/oryx/blob/master/app/oryx-app-serving/src/test/java/com/cloudera/oryx/app/traffic/TrafficUtil.java | Apache-2.0 |
public static void main(String[] args) throws Exception {
try (BatchLayer<?,?,?> batchLayer = new BatchLayer<>(ConfigUtils.getDefault())) {
HadoopUtils.closeAtShutdown(batchLayer);
batchLayer.start();
batchLayer.await();
}
} | Runs {@link BatchLayer} from the command line. It will use configuration as loaded
by TypeSafe Config's {@code ConfigFactory}. | main | java | OryxProject/oryx | deploy/oryx-batch/src/main/java/com/cloudera/oryx/batch/Main.java | https://github.com/OryxProject/oryx/blob/master/deploy/oryx-batch/src/main/java/com/cloudera/oryx/batch/Main.java | Apache-2.0 |
public static void main(String[] args) throws Exception {
try (ServingLayer servingLayer = new ServingLayer(ConfigUtils.getDefault())) {
JVMUtils.closeAtShutdown(servingLayer);
servingLayer.start();
servingLayer.await();
}
} | Runs {@link ServingLayer} from the command line. It will use configuration as loaded
by TypeSafe Config's {@code ConfigFactory}. | main | java | OryxProject/oryx | deploy/oryx-serving/src/main/java/com/cloudera/oryx/serving/Main.java | https://github.com/OryxProject/oryx/blob/master/deploy/oryx-serving/src/main/java/com/cloudera/oryx/serving/Main.java | Apache-2.0 |
public static void main(String[] args) throws Exception {
try (SpeedLayer<?,?,?> speedLayer = new SpeedLayer<>(ConfigUtils.getDefault())) {
HadoopUtils.closeAtShutdown(speedLayer);
speedLayer.start();
speedLayer.await();
}
} | Runs {@link SpeedLayer} from the command line. It will use configuration as loaded
by TypeSafe Config's {@code ConfigFactory}. | main | java | OryxProject/oryx | deploy/oryx-speed/src/main/java/com/cloudera/oryx/speed/Main.java | https://github.com/OryxProject/oryx/blob/master/deploy/oryx-speed/src/main/java/com/cloudera/oryx/speed/Main.java | Apache-2.0 |
public static void maybeCreateTopic(String zkServers, String topic, int partitions) {
maybeCreateTopic(zkServers, topic, partitions, new Properties());
} | @param zkServers Zookeeper server string: host1:port1[,host2:port2,...]
@param topic topic to create (if not already existing)
@param partitions number of topic partitions | maybeCreateTopic | java | OryxProject/oryx | framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | Apache-2.0 |
public static void maybeCreateTopic(String zkServers,
String topic,
int partitions,
Properties topicProperties) {
ZkUtils zkUtils = ZkUtils.apply(zkServers, ZK_TIMEOUT_MSEC, ZK_TIMEOUT_MSEC, false);
try {
if (AdminUtils.topicExists(zkUtils, topic)) {
log.info("No need to create topic {} as it already exists", topic);
} else {
log.info("Creating topic {} with {} partition(s)", topic, partitions);
try {
AdminUtils.createTopic(
zkUtils, topic, partitions, 1, topicProperties, RackAwareMode.Enforced$.MODULE$);
log.info("Created topic {}", topic);
} catch (TopicExistsException re) {
log.info("Topic {} already exists", topic);
}
}
} finally {
zkUtils.close();
}
} | @param zkServers Zookeeper server string: host1:port1[,host2:port2,...]
@param topic topic to create (if not already existing)
@param partitions number of topic partitions
@param topicProperties optional topic config properties | maybeCreateTopic | java | OryxProject/oryx | framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | Apache-2.0 |
public static boolean topicExists(String zkServers, String topic) {
ZkUtils zkUtils = ZkUtils.apply(zkServers, ZK_TIMEOUT_MSEC, ZK_TIMEOUT_MSEC, false);
try {
return AdminUtils.topicExists(zkUtils, topic);
} finally {
zkUtils.close();
}
} | @param zkServers Zookeeper server string: host1:port1[,host2:port2,...]
@param topic topic to check for existence
@return {@code true} if and only if the given topic exists | topicExists | java | OryxProject/oryx | framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | Apache-2.0 |
public static void deleteTopic(String zkServers, String topic) {
ZkUtils zkUtils = ZkUtils.apply(zkServers, ZK_TIMEOUT_MSEC, ZK_TIMEOUT_MSEC, false);
try {
if (AdminUtils.topicExists(zkUtils, topic)) {
log.info("Deleting topic {}", topic);
AdminUtils.deleteTopic(zkUtils, topic);
log.info("Deleted Zookeeper topic {}", topic);
} else {
log.info("No need to delete topic {} as it does not exist", topic);
}
} finally {
zkUtils.close();
}
} | @param zkServers Zookeeper server string: host1:port1[,host2:port2,...]
@param topic topic to delete, if it exists | deleteTopic | java | OryxProject/oryx | framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | Apache-2.0 |
public static void setOffsets(String zkServers,
String groupID,
Map<Pair<String,Integer>,Long> offsets) {
ZkUtils zkUtils = ZkUtils.apply(zkServers, ZK_TIMEOUT_MSEC, ZK_TIMEOUT_MSEC, false);
try {
offsets.forEach((topicAndPartition, offset) -> {
String topic = topicAndPartition.getFirst();
int partition = topicAndPartition.getSecond();
String partitionOffsetPath = "/consumers/" + groupID + "/offsets/" + topic + '/' + partition;
zkUtils.updatePersistentPath(partitionOffsetPath,
Long.toString(offset),
ZkUtils$.MODULE$.defaultAcls(false, ""));
});
} finally {
zkUtils.close();
}
} | @param zkServers Zookeeper server string: host1:port1[,host2:port2,...]
@param groupID consumer group to update
@param offsets mapping of (topic and) partition to offset to push to Zookeeper | setOffsets | java | OryxProject/oryx | framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/main/java/com/cloudera/oryx/kafka/util/KafkaUtils.java | Apache-2.0 |
@Override
public CloseableIterator<KeyMessage<String,String>> iterator() {
KafkaConsumer<String,String> consumer = new KafkaConsumer<>(
ConfigUtils.keyValueToProperties(
"group.id", "OryxGroup-ConsumeData",
"bootstrap.servers", "localhost:" + kafkaPort,
"key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer",
"value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer",
"max.partition.fetch.bytes", maxMessageSize,
"auto.offset.reset", "earliest" // For tests, always start at the beginning
));
consumer.subscribe(Collections.singletonList(topic));
return new ConsumeDataIterator<>(consumer);
} | A iterator that consumes data from a Kafka topic. | iterator | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ConsumeData.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ConsumeData.java | Apache-2.0 |
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
return new Pair<>(Integer.toString(id),
id + "," +
random.nextInt(100) + ',' +
random.nextBoolean() + ',' +
random.nextGaussian());
} | Interface which generates one random datum. | generate | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/DefaultCSVDatumGenerator.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/DefaultCSVDatumGenerator.java | Apache-2.0 |
int getPort() {
return port;
} | Creates an instance that will listen on the given port and connect to the given
Zookeeper port.
@param port port for Kafka broker to listen on
@param zkPort port on which Zookeeper is listening | getPort | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalKafkaBroker.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalKafkaBroker.java | Apache-2.0 |
public synchronized void start() throws IOException {
log.info("Starting Kafka broker on port {}", port);
logsDir = Files.createTempDirectory(LocalKafkaBroker.class.getSimpleName());
logsDir.toFile().deleteOnExit();
kafkaServer = new KafkaServerStartable(new KafkaConfig(ConfigUtils.keyValueToProperties(
"broker.id", TEST_BROKER_ID,
"log.dirs", logsDir.toAbsolutePath(),
"listeners", "PLAINTEXT://:" + port,
"zookeeper.connect", "localhost:" + zkPort,
"message.max.bytes", 1 << 26,
"replica.fetch.max.bytes", 1 << 26,
"offsets.topic.replication.factor", 1
), false));
kafkaServer.startup();
} | Starts the Kafka broker.
@throws IOException if an error occurs during initialization | start | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalKafkaBroker.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalKafkaBroker.java | Apache-2.0 |
public synchronized void start() throws IOException, InterruptedException {
log.info("Starting Zookeeper on port {}", port);
dataDir = Files.createTempDirectory(LocalZKServer.class.getSimpleName());
dataDir.toFile().deleteOnExit();
QuorumPeerConfig quorumConfig = new QuorumPeerConfig();
try {
quorumConfig.parseProperties(ConfigUtils.keyValueToProperties(
"dataDir", dataDir.toAbsolutePath(),
"clientPort", port
));
} catch (QuorumPeerConfig.ConfigException e) {
throw new IllegalArgumentException(e);
}
purgeManager =
new DatadirCleanupManager(quorumConfig.getDataDir(),
quorumConfig.getDataLogDir(),
quorumConfig.getSnapRetainCount(),
quorumConfig.getPurgeInterval());
purgeManager.start();
ServerConfig serverConfig = new ServerConfig();
serverConfig.readFrom(quorumConfig);
zkServer = new ZooKeeperServer();
zkServer.setTickTime(serverConfig.getTickTime());
zkServer.setMinSessionTimeout(serverConfig.getMinSessionTimeout());
zkServer.setMaxSessionTimeout(serverConfig.getMaxSessionTimeout());
// These two ServerConfig methods returned String in 3.4.x and File in 3.5.x
transactionLog = new FileTxnSnapLog(new File(serverConfig.getDataLogDir().toString()),
new File(serverConfig.getDataDir().toString()));
zkServer.setTxnLogFactory(transactionLog);
connectionFactory = ServerCnxnFactory.createFactory();
connectionFactory.configure(serverConfig.getClientPortAddress(), serverConfig.getMaxClientCnxns());
connectionFactory.startup(zkServer);
} | Starts Zookeeper.
@throws IOException if an error occurs during initialization
@throws InterruptedException if an error occurs during initialization | start | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalZKServer.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/LocalZKServer.java | Apache-2.0 |
@Test
public void testProduceConsume() throws Exception {
int zkPort = IOUtils.chooseFreePort();
int kafkaBrokerPort = IOUtils.chooseFreePort();
try (LocalZKServer localZKServer = new LocalZKServer(zkPort);
LocalKafkaBroker localKafkaBroker = new LocalKafkaBroker(kafkaBrokerPort, zkPort)) {
localZKServer.start();
localKafkaBroker.start();
String zkHostPort = "localhost:" + zkPort;
KafkaUtils.deleteTopic(zkHostPort, TOPIC);
KafkaUtils.maybeCreateTopic(zkHostPort, TOPIC, 4);
ProduceData produce = new ProduceData(new DefaultCSVDatumGenerator(),
localKafkaBroker.getPort(),
TOPIC,
NUM_DATA,
0);
List<String> keys;
try (CloseableIterator<KeyMessage<String,String>> data = new ConsumeData(TOPIC, kafkaBrokerPort).iterator()) {
log.info("Starting consumer thread");
ConsumeTopicRunnable consumeTopic = new ConsumeTopicRunnable(data, NUM_DATA);
new Thread(LoggingCallable.log(consumeTopic).asRunnable(), "ConsumeTopicThread").start();
consumeTopic.awaitRun();
log.info("Producing data");
produce.start();
consumeTopic.awaitMessages();
keys = consumeTopic.getKeys();
} finally {
KafkaUtils.deleteTopic(zkHostPort, TOPIC);
}
if (keys.size() != NUM_DATA) {
log.info("keys = {}", keys);
assertEquals(NUM_DATA, keys.size());
}
for (int i = 0; i < NUM_DATA; i++) {
assertContains(keys, Integer.toString(i));
}
}
} | Tests {@link ProduceData} and {@link ConsumeData} together. | testProduceConsume | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ProduceConsumeIT.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ProduceConsumeIT.java | Apache-2.0 |
public void start() throws InterruptedException {
RandomGenerator random = RandomManager.getRandom();
Properties props = ConfigUtils.keyValueToProperties(
"bootstrap.servers", "localhost:" + kafkaPort,
"key.serializer", "org.apache.kafka.common.serialization.StringSerializer",
"value.serializer", "org.apache.kafka.common.serialization.StringSerializer",
"compression.type", "gzip",
"linger.ms", 0,
"batch.size", 0,
"acks", 1,
"max.request.size", 1 << 26 // TODO
);
try (Producer<String,String> producer = new KafkaProducer<>(props)) {
for (int i = 0; i < howMany; i++) {
Pair<String,String> datum = datumGenerator.generate(i, random);
ProducerRecord<String,String> record =
new ProducerRecord<>(topic, datum.getFirst(), datum.getSecond());
producer.send(record);
log.debug("Sent datum {} = {}", record.key(), record.value());
if (intervalMsec > 0) {
Thread.sleep(intervalMsec);
}
}
}
} | A process that will continually send data to a Kafka topic. This is useful for testing
purposes. It will send strings, CSV-formatted random feature data, like "3,true,-0.135". | start | java | OryxProject/oryx | framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ProduceData.java | https://github.com/OryxProject/oryx/blob/master/framework/kafka-util/src/test/java/com/cloudera/oryx/kafka/util/ProduceData.java | Apache-2.0 |
@SuppressWarnings("unchecked")
@PostConstruct
protected void init() {
servingModelManager = Objects.requireNonNull(
(ServingModelManager<?>) servletContext.getAttribute(MODEL_MANAGER_KEY),
"No ServingModelManager");
inputProducer = Objects.requireNonNull(
(TopicProducer<?,?>) servletContext.getAttribute(INPUT_PRODUCER_KEY),
"No input producer available; read-only mode?");
} | A utility class that can serve as a superclass of Serving Layer application endpoints.
It handles loading provided objects like a {@link ServingModelManager}.
@since 2.0.0 | init | java | OryxProject/oryx | framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | Apache-2.0 |
protected final ServingModelManager<?> getServingModelManager() {
return servingModelManager;
} | @return a reference to the {@link ServingModelManager} for the app, configured in the
{@link ServletContext} under key {@link #MODEL_MANAGER_KEY}
@since 2.0.0 | getServingModelManager | java | OryxProject/oryx | framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | Apache-2.0 |
protected final TopicProducer<?,?> getInputProducer() {
return inputProducer;
} | @return a reference to the {@link TopicProducer} for the app, configured in the
{@link ServletContext} under key {@link #INPUT_PRODUCER_KEY}
@since 2.0.0 | getInputProducer | java | OryxProject/oryx | framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxResource.java | Apache-2.0 |
public Response.Status getStatusCode() {
return statusCode;
} | @return HTTP status that this exception corresponds to
@since 2.2.0 | getStatusCode | java | OryxProject/oryx | framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxServingException.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-api/src/main/java/com/cloudera/oryx/api/serving/OryxServingException.java | Apache-2.0 |
@Override
public void consume(Iterator<KeyMessage<String,U>> updateIterator, Configuration hadoopConf) throws IOException {
while (updateIterator.hasNext()) {
try {
KeyMessage<String,U> km = updateIterator.next();
String key = km.getKey();
U message = km.getMessage();
Objects.requireNonNull(key);
consumeKeyMessage(key, message, hadoopConf);
} catch (Exception e) {
log.warn("Exception while processing message; continuing", e);
}
}
} | Convenience implementation of {@link SpeedModelManager} that provides default implementations.
@param <K> type of key read from input topic
@param <M> type of message read from input topic
@param <U> type of update message read/written
@since 2.3.0 | consume | java | OryxProject/oryx | framework/oryx-api/src/main/java/com/cloudera/oryx/api/speed/AbstractSpeedModelManager.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-api/src/main/java/com/cloudera/oryx/api/speed/AbstractSpeedModelManager.java | Apache-2.0 |
public static <C extends Comparable<C>,D> Comparator<Pair<C,D>> orderByFirst(SortOrder order) {
Comparator<Pair<C,D>> ordering = Comparator.comparing(Pair::getFirst);
if (order == SortOrder.DESCENDING) {
ordering = ordering.reversed();
}
return Comparator.nullsLast(ordering);
} | @param order whether to sort ascending or descending; {@code null} comes last
@param <C> type of first element in {@link Pair}s to be compared
@param <D> type of second element in {@link Pair}s to be compared
@return an ordering on {@link Pair}s by first element as a {@link Comparator} | orderByFirst | java | OryxProject/oryx | framework/oryx-common/src/main/java/com/cloudera/oryx/common/collection/Pairs.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/collection/Pairs.java | Apache-2.0 |
public static <C,D extends Comparable<D>> Comparator<Pair<C,D>> orderBySecond(SortOrder order) {
Comparator<Pair<C,D>> ordering = Comparator.comparing(Pair::getSecond);
if (order == SortOrder.DESCENDING) {
ordering = ordering.reversed();
}
return Comparator.nullsLast(ordering);
} | @param order whether to sort ascending or descending; {@code null} comes last
@param <C> type of first element in {@link Pair}s to be compared
@param <D> type of second element in {@link Pair}s to be compared
@return an ordering on {@link Pair}s by second element as a {@link Comparator} | orderBySecond | java | OryxProject/oryx | framework/oryx-common/src/main/java/com/cloudera/oryx/common/collection/Pairs.java | https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/collection/Pairs.java | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.