/** * 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.clustering.lda; import com.google.common.base.Preconditions; import org.apache.mahout.math.Matrix; import org.apache.mahout.math.Vector; import org.apache.mahout.math.stats.Sampler; import java.util.Random; /** * Takes in a {@link Matrix} of topic distributions (such as generated by {@link LDADriver}, * {@link org.apache.mahout.clustering.lda.cvb.CVB0Driver} or * {@link org.apache.mahout.clustering.lda.cvb.InMemoryCollapsedVariationalBayes0}, and constructs * a set of samplers over this distribution, which may be sampled from by providing a distribution * over topics, and a number of samples desired */ public class LDASampler { private final Random random; private final Sampler[] samplers; public LDASampler(Matrix model, Random random) { this.random = random; samplers = new Sampler[model.numRows()]; for(int i = 0; i < samplers.length; i++) { samplers[i] = new Sampler(random, model.viewRow(i)); } } /** * * @param topicDistribution vector of p(topicId) for all topicId < model.numTopics() * @param numSamples the number of times to sample (with replacement) from the model * @return array of length numSamples, with each entry being a sample from the model. There * may be repeats */ public int[] sample(Vector topicDistribution, int numSamples) { Preconditions.checkNotNull(topicDistribution); Preconditions.checkArgument(numSamples > 0, "numSamples must be positive"); Preconditions.checkArgument(topicDistribution.size() == samplers.length, "topicDistribution must have same cardinality as the sampling model"); int[] samples = new int[numSamples]; Sampler topicSampler = new Sampler(random, topicDistribution); for(int i = 0; i < numSamples; i++) { samples[i] = samplers[topicSampler.sample()].sample(); } return samples; } }