本文整理汇总了Java中weka.core.Utils.maxIndex方法的典型用法代码示例。如果您正苦于以下问题:Java Utils.maxIndex方法的具体用法?Java Utils.maxIndex怎么用?Java Utils.maxIndex使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weka.core.Utils
的用法示例。
在下文中一共展示了Utils.maxIndex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: newRule
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Create a rule branching on this attribute.
*
* @param attr the attribute to branch on
* @param data the data to be used for creating the rule
* @return the generated rule
* @throws Exception if the rule can't be built successfully
*/
public OneRRule newRule(Attribute attr, Instances data) throws Exception {
OneRRule r;
// ... create array to hold the missing value counts
int[] missingValueCounts = new int[data.classAttribute().numValues()];
if (attr.isNominal()) {
r = newNominalRule(attr, data, missingValueCounts);
} else {
r = newNumericRule(attr, data, missingValueCounts);
}
r.m_missingValueClass = Utils.maxIndex(missingValueCounts);
if (missingValueCounts[r.m_missingValueClass] == 0) {
r.m_missingValueClass = -1; // signal for no missing value class
} else {
r.m_correct += missingValueCounts[r.m_missingValueClass];
}
return r;
}
示例2: utilityInstance
import weka.core.Utils; //导入方法依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public double utilityInstance(Instance instance) {
double[] probs = distributionForInstance(instance);
// determine the class with the highest probability
int ind1 = Utils.maxIndex(probs);
double max1 = probs[ind1];
probs[ind1] = 0;
// determine the second class with the highest probability
int ind2 = Utils.maxIndex(probs);
double max2 = probs[ind2];
return max1 - max2;
}
示例3: distributionForInstance
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Calculates the class membership probabilities for the given test
* instance.
*
* @param instance the instance to be classified
* @return predicted class probability distribution
* @throws Exception if there is a problem generating the prediction
*/
public double [] distributionForInstance(Instance instance) throws Exception
{
double[] probOfClassGivenDoc = new double[m_numClasses];
//calculate the array of log(Pr[D|C])
double[] logDocGivenClass = new double[m_numClasses];
for(int h = 0; h<m_numClasses; h++)
logDocGivenClass[h] = probOfDocGivenClass(instance, h);
double max = logDocGivenClass[Utils.maxIndex(logDocGivenClass)];
double probOfDoc = 0.0;
for(int i = 0; i<m_numClasses; i++)
{
probOfClassGivenDoc[i] = Math.exp(logDocGivenClass[i] - max) * m_probOfClass[i];
probOfDoc += probOfClassGivenDoc[i];
}
Utils.normalize(probOfClassGivenDoc,probOfDoc);
return probOfClassGivenDoc;
}
示例4: getVotesForInstance
import weka.core.Utils; //导入方法依赖的package包/类
@Override
public double[] getVotesForInstance(Instance inst) {
// TODO Auto-generated method stub
// increase no. of seen intances
totalSeenInstances++;
// check if there is any rules that cover the instance
ArrayList<Rule> coveredRules = RulesCoveredInstance(inst);
// logger.debug("No. Rules cover instance: " + coveredRules.size());
// logger.debug(inst);
// return prediction if there are rules that cover the instance
if(coveredRules.size() > 0){
actualAttempts++;
double[] classPrediction = new double[inst.numClasses()];
// vote class labels from all available rules
for (Rule rule : coveredRules) {
classPrediction[(int)rule.classification]++;
// logger.debug(rule.printRule());
}
// actual attempt
if(Utils.maxIndex(classPrediction) == (int) inst.classValue()){
actualAttemptsCorrectlyClassified++;
}
return classPrediction ;
}
// otherwise, return the majority class
return observedClassDistribution.getArrayCopy();
}
示例5: toGraph
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Outputs one node for graph.
*
* @param text the buffer to append the output to
* @param num unique node id
* @return the next node id
* @throws Exception if generation fails
*/
public int toGraph(StringBuffer text, int num) throws Exception {
int maxIndex = Utils.maxIndex(m_ClassDistribution);
String classValue = m_Info.classAttribute().isNominal() ? m_Info
.classAttribute().value(maxIndex) : Utils.doubleToString(
m_ClassDistribution[0], 2);
num++;
if (m_Attribute == -1) {
text.append("N" + Integer.toHexString(hashCode()) + " [label=\"" + num
+ ": " + classValue + "\"" + "shape=box]\n");
} else {
text.append("N" + Integer.toHexString(hashCode()) + " [label=\"" + num
+ ": " + classValue + "\"]\n");
for (int i = 0; i < m_Successors.length; i++) {
text.append("N" + Integer.toHexString(hashCode()) + "->" + "N"
+ Integer.toHexString(m_Successors[i].hashCode()) + " [label=\""
+ m_Info.attribute(m_Attribute).name());
if (m_Info.attribute(m_Attribute).isNumeric()) {
if (i == 0) {
text.append(" < " + Utils.doubleToString(m_SplitPoint, 2));
} else {
text.append(" >= " + Utils.doubleToString(m_SplitPoint, 2));
}
} else {
text.append(" = " + m_Info.attribute(m_Attribute).value(i));
}
text.append("\"]\n");
num = m_Successors[i].toGraph(text, num);
}
}
return num;
}
示例6: leafString
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Outputs a leaf.
*
* @return the leaf as string
* @throws Exception if generation fails
*/
protected String leafString() throws Exception {
double sum = 0, maxCount = 0;
int maxIndex = 0;
double classMean = 0;
double avgError = 0;
if (m_ClassDistribution != null) {
if (m_Info.classAttribute().isNominal()) {
sum = Utils.sum(m_ClassDistribution);
maxIndex = Utils.maxIndex(m_ClassDistribution);
maxCount = m_ClassDistribution[maxIndex];
} else {
classMean = m_ClassDistribution[0];
if (m_Distribution[1] > 0) {
avgError = m_Distribution[0] / m_Distribution[1];
}
}
}
if (m_Info.classAttribute().isNumeric()) {
return " : " + Utils.doubleToString(classMean, 2) + " ("
+ Utils.doubleToString(m_Distribution[1], 2) + "/"
+ Utils.doubleToString(avgError, 2) + ")";
}
return " : " + m_Info.classAttribute().value(maxIndex) + " ("
+ Utils.doubleToString(sum, 2) + "/"
+ Utils.doubleToString(sum - maxCount, 2) + ")";
}
示例7: call
import weka.core.Utils; //导入方法依赖的package包/类
/** Determine predictions for a single instance (defined in "instanceIdx"). */
public Double call() throws Exception{
double[] classProbs = null;
classProbs = new double[data.numClasses];
int numVotes = 0;
for (int treeIdx = 0; treeIdx < m_Classifiers.length; treeIdx++){
if ( inBag[treeIdx][instanceIdx] ) {
continue;
}
numVotes++;
FastRandomTree aTree;
if ( m_Classifiers[treeIdx] instanceof FastRandomTree)
aTree = (FastRandomTree) m_Classifiers[treeIdx];
else
throw new IllegalArgumentException("Only FastRandomTrees accepted in the VotesCollector.");
double[] curDist;
curDist = aTree.distributionForInstanceInDataCache(data, instanceIdx);
for(int classIdx = 0; classIdx < curDist.length; classIdx++) {
classProbs[classIdx] += curDist[classIdx];
}
}
double vote;
//if(regression)
// vote = regrValue / numVotes; // average - for regression
//else
vote = Utils.maxIndex(classProbs); // consensus - for classification
return vote;
}
示例8: distributionForInstance
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Calculates the class membership probabilities for the given test instance.
*
* @param instance the instance to be classified
* @return predicted class probability distribution
* @throws Exception if there is a problem generating the prediction
*/
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
double[] probOfClassGivenDoc = new double[m_numClasses];
// calculate the array of log(Pr[D|C])
double[] logDocGivenClass = new double[m_numClasses];
for (int c = 0; c < m_numClasses; c++) {
logDocGivenClass[c] += Math.log(m_probOfClass[c]);
int allWords = 0;
for (int i = 0; i < instance.numValues(); i++) {
if (instance.index(i) == instance.classIndex()) {
continue;
}
double frequencies = instance.valueSparse(i);
allWords += frequencies;
logDocGivenClass[c] +=
frequencies * Math.log(m_probOfWordGivenClass[c][instance.index(i)]);
}
logDocGivenClass[c] -= allWords * Math.log(m_wordsPerClass[c]);
}
double max = logDocGivenClass[Utils.maxIndex(logDocGivenClass)];
for (int i = 0; i < m_numClasses; i++) {
probOfClassGivenDoc[i] = Math.exp(logDocGivenClass[i] - max);
}
Utils.normalize(probOfClassGivenDoc);
return probOfClassGivenDoc;
}
开发者ID:mydzigear,项目名称:repo.kmeanspp.silhouette_score,代码行数:38,代码来源:NaiveBayesMultinomialUpdateable.java
示例9: logDensity
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Computes log of density for given value.
*/
public double logDensity(double value) {
double[] a = logJointDensities(value);
double max = a[Utils.maxIndex(a)];
double sum = 0.0;
for(int i = 0; i < a.length; i++) {
sum += Math.exp(a[i] - max);
}
return max + Math.log(sum);
}
示例10: objectiveFunction
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Evaluate objective function
*
* @param x the current values of variables
* @return the value of the objective function
*/
protected double objectiveFunction(double[] x) {
double nll = 0; // -LogLikelihood
int dim = m_NumPredictors + 1; // Number of variables per class
for (int i = 0; i < cls.length; i++) { // ith instance
double[] exp = new double[m_NumClasses - 1];
int index;
for (int offset = 0; offset < m_NumClasses - 1; offset++) {
index = offset * dim;
for (int j = 0; j < dim; j++) {
exp[offset] += m_Data[i][j] * x[index + j];
}
}
double max = exp[Utils.maxIndex(exp)];
double denom = Math.exp(-max);
double num;
if (cls[i] == m_NumClasses - 1) { // Class of this instance
num = -max;
} else {
num = exp[cls[i]] - max;
}
for (int offset = 0; offset < m_NumClasses - 1; offset++) {
denom += Math.exp(exp[offset] - max);
}
nll -= weights[i] * (num - Math.log(denom)); // Weighted NLL
}
// Ridge: note that intercepts NOT included
for (int offset = 0; offset < m_NumClasses - 1; offset++) {
for (int r = 1; r < dim; r++) {
nll += m_Ridge * x[offset * dim + r] * x[offset * dim + r];
}
}
return nll;
}
示例11: evaluationForSingleInstance
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Evaluates the supplied distribution on a single instance.
*
* @param dist the supplied distribution
* @param instance the test instance to be classified
* @param storePredictions whether to store predictions for nominal classifier
* @return the prediction
* @throws Exception if model could not be evaluated successfully
*/
public double evaluationForSingleInstance(double[] dist, Instance instance,
boolean storePredictions) throws Exception {
double pred;
if (m_ClassIsNominal) {
pred = Utils.maxIndex(dist);
if (dist[(int) pred] <= 0) {
pred = Utils.missingValue();
}
updateStatsForClassifier(dist, instance);
if (storePredictions && !m_DiscardPredictions) {
if (m_Predictions == null) {
m_Predictions = new ArrayList<Prediction>();
}
m_Predictions.add(new NominalPrediction(instance.classValue(), dist,
instance.weight()));
}
} else {
pred = dist[0];
updateStatsForPredictor(pred, instance);
if (storePredictions && !m_DiscardPredictions) {
if (m_Predictions == null) {
m_Predictions = new ArrayList<Prediction>();
}
m_Predictions.add(new NumericPrediction(instance.classValue(), pred,
instance.weight()));
}
}
return pred;
}
示例12: classWithLargestValueInDistribution
import weka.core.Utils; //导入方法依赖的package包/类
public int classWithLargestValueInDistribution(){
return Utils.maxIndex(classDistribution);
}
示例13: call
import weka.core.Utils; //导入方法依赖的package包/类
/** Determine predictions for a single instance. */
public Double call() throws Exception{
boolean regression = data.classAttribute().isNumeric();
double[] classProbs = null;
double regrValue = 0;
if ( !regression )
classProbs = new double[data.numClasses()];
int numVotes = 0;
for(int treeIdx = 0; treeIdx < m_Classifiers.length; treeIdx++){
if ( inBag[treeIdx][instanceIdx] )
continue;
numVotes++;
FastRandomTree aTree;
if ( m_Classifiers[treeIdx] instanceof FastRandomTree)
aTree = (FastRandomTree) m_Classifiers[treeIdx];
else
throw new IllegalArgumentException("Only FastRandomTrees accepted in the VotesCollector.");
if ( regression ) {
double curVote;
curVote = aTree.classifyInstance(data.instance(instanceIdx));
regrValue += curVote;
} else {
double[] curDist = aTree.distributionForInstance(data.instance(instanceIdx));
for(int classIdx = 0; classIdx < curDist.length; classIdx++)
classProbs[classIdx] += curDist[classIdx];
}
}
double vote;
if(regression)
vote = regrValue / numVotes; // average - for regression
else
vote = Utils.maxIndex(classProbs); // consensus - for classification
return vote;
}
示例14: leafString
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Outputs description of a leaf node.
*
* @param parent the parent of the node
* @return the description of the node
* @throws Exception if generation fails
*/
protected String leafString(Tree parent) throws Exception {
if (m_Info.classAttribute().isNumeric()) {
double classMean;
if (m_ClassProbs == null) {
classMean = parent.m_ClassProbs[0];
} else {
classMean = m_ClassProbs[0];
}
StringBuffer buffer = new StringBuffer();
buffer.append(" : " + Utils.doubleToString(classMean, 2));
double avgError = 0;
if (m_Distribution[1] > 0) {
avgError = m_Distribution[0] / m_Distribution[1];
}
buffer.append(" (" + Utils.doubleToString(m_Distribution[1], 2) + "/"
+ Utils.doubleToString(avgError, 2) + ")");
avgError = 0;
if (m_HoldOutDist[0] > 0) {
avgError = m_HoldOutError / m_HoldOutDist[0];
}
buffer.append(" [" + Utils.doubleToString(m_HoldOutDist[0], 2) + "/"
+ Utils.doubleToString(avgError, 2) + "]");
return buffer.toString();
} else {
int maxIndex;
if (m_ClassProbs == null) {
maxIndex = Utils.maxIndex(parent.m_ClassProbs);
} else {
maxIndex = Utils.maxIndex(m_ClassProbs);
}
return " : "
+ m_Info.classAttribute().value(maxIndex)
+ " ("
+ Utils.doubleToString(Utils.sum(m_Distribution), 2)
+ "/"
+ Utils.doubleToString(
(Utils.sum(m_Distribution) - m_Distribution[maxIndex]), 2)
+ ")"
+ " ["
+ Utils.doubleToString(Utils.sum(m_HoldOutDist), 2)
+ "/"
+ Utils.doubleToString(
(Utils.sum(m_HoldOutDist) - m_HoldOutDist[maxIndex]), 2) + "]";
}
}
示例15: batchFinished
import weka.core.Utils; //导入方法依赖的package包/类
/**
* Signify that this batch of input to the filter is finished.
* If the filter requires all instances prior to filtering,
* output() may now be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined
*/
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_ModesAndMeans == null) {
// Compute modes and means
double sumOfWeights = getInputFormat().sumOfWeights();
double[][] counts = new double[getInputFormat().numAttributes()][];
for (int i = 0; i < getInputFormat().numAttributes(); i++) {
if (getInputFormat().attribute(i).isNominal()) {
counts[i] = new double[getInputFormat().attribute(i).numValues()];
if (counts[i].length > 0)
counts[i][0] = sumOfWeights;
}
}
double[] sums = new double[getInputFormat().numAttributes()];
for (int i = 0; i < sums.length; i++) {
sums[i] = sumOfWeights;
}
double[] results = new double[getInputFormat().numAttributes()];
for (int j = 0; j < getInputFormat().numInstances(); j++) {
Instance inst = getInputFormat().instance(j);
for (int i = 0; i < inst.numValues(); i++) {
if (!inst.isMissingSparse(i)) {
double value = inst.valueSparse(i);
if (inst.attributeSparse(i).isNominal()) {
if (counts[inst.index(i)].length > 0) {
counts[inst.index(i)][(int)value] += inst.weight();
counts[inst.index(i)][0] -= inst.weight();
}
} else if (inst.attributeSparse(i).isNumeric()) {
results[inst.index(i)] += inst.weight() * inst.valueSparse(i);
}
} else {
if (inst.attributeSparse(i).isNominal()) {
if (counts[inst.index(i)].length > 0) {
counts[inst.index(i)][0] -= inst.weight();
}
} else if (inst.attributeSparse(i).isNumeric()) {
sums[inst.index(i)] -= inst.weight();
}
}
}
}
m_ModesAndMeans = new double[getInputFormat().numAttributes()];
for (int i = 0; i < getInputFormat().numAttributes(); i++) {
if (getInputFormat().attribute(i).isNominal()) {
if (counts[i].length == 0)
m_ModesAndMeans[i] = Utils.missingValue();
else
m_ModesAndMeans[i] = (double)Utils.maxIndex(counts[i]);
} else if (getInputFormat().attribute(i).isNumeric()) {
if (Utils.gr(sums[i], 0)) {
m_ModesAndMeans[i] = results[i] / sums[i];
}
}
}
// Convert pending input instances
for(int i = 0; i < getInputFormat().numInstances(); i++) {
convertInstance(getInputFormat().instance(i));
}
}
// Free memory
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}