org.apache.mahout.utils.clustering.JsonClusterWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mahout-integration Show documentation
Show all versions of mahout-integration Show documentation
Optional components of Mahout which generally support interaction with third party systems,
formats, APIs, etc.
The newest version!
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.utils.clustering;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.mahout.clustering.AbstractCluster;
import org.apache.mahout.clustering.Cluster;
import org.apache.mahout.clustering.classify.WeightedPropertyVectorWritable;
import org.apache.mahout.clustering.iterator.ClusterWritable;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.math.NamedVector;
import org.apache.mahout.math.Vector;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Dump cluster info to JSON formatted lines. Heavily inspired by
* ClusterDumperWriter.java and CSVClusterWriter.java
*
*/
public class JsonClusterWriter extends AbstractClusterWriter {
private final String[] dictionary;
private final int numTopFeatures;
private final ObjectMapper jxn;
private static final Logger log = LoggerFactory.getLogger(JsonClusterWriter.class);
private static final Pattern VEC_PATTERN = Pattern.compile("\\{|\\:|\\,|\\}");
public JsonClusterWriter(Writer writer,
Map> clusterIdToPoints,
DistanceMeasure measure, int numTopFeatures, String[] dictionary) {
super(writer, clusterIdToPoints, measure);
this.numTopFeatures = numTopFeatures;
this.dictionary = dictionary;
jxn = new ObjectMapper();
}
/**
* Generate HashMap with cluster info and write as a single JSON formatted
* line
*/
@Override
public void write(ClusterWritable clusterWritable) throws IOException {
Map res = new HashMap<>();
// get top terms
if (dictionary != null) {
List