本文整理汇总了C#中weka.core.Instances.attribute方法的典型用法代码示例。如果您正苦于以下问题:C# Instances.attribute方法的具体用法?C# Instances.attribute怎么用?C# Instances.attribute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weka.core.Instances
的用法示例。
在下文中一共展示了Instances.attribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Build
public void Build()
{
this.featureIndex = new int[this.features.Count];
for(int i=0;(i< this.features.Count);i++)
{
for (int j = 0; (j < Extractor.ArffAttributeLabels.Length); j++)
if (((string)this.features[i]).Equals(Extractor.ArffAttributeLabels[j]))
{
this.featureIndex[i] = j;
break;
}
}
instances = new Instances(new StreamReader(this.filename));
instances.Class = instances.attribute(this.features.Count);
classifier = new J48();
classifier.buildClassifier(instances);
//setup the feature vector
//fvWekaAttributes = new FastVector(this.features.Count + 1);
//for (i = 0; (i < this.features.Count); i++)
// fvWekaAttributes.addElement(new weka.core.Attribute(this.features[i]));
//Setup the class attribute
//FastVector fvClassVal = new FastVector();
//for (i = 0; (i < this.classes.Count); i++)
// fvClassVal.addElement(this.classes[i]);
//weka.core.Attribute ClassAttribute = new weka.core.Attribute("activity", fvClassVal);
}
示例2: loadLabelsMeta
private LabelsMetaData loadLabelsMeta(Instances data, int numLabels)
{
LabelsMetaDataImpl labelsData = new LabelsMetaDataImpl();
int numAttributes = data.numAttributes();
for (int index = numAttributes - numLabels; index < numAttributes; index++) {
String attrName = data.attribute(index).name();
labelsData.addRootNode(new LabelNodeImpl(attrName));
}
return labelsData;
}
示例3: minsAndMaxs
/// <summary> Returns the minsAndMaxs of the index.th subset.</summary>
public double[][] minsAndMaxs(Instances data, double[][] minsAndMaxs, int index)
{
double[][] newMinsAndMaxs = new double[data.numAttributes()][];
for (int i = 0; i < data.numAttributes(); i++)
{
newMinsAndMaxs[i] = new double[2];
}
for (int i = 0; i < data.numAttributes(); i++)
{
newMinsAndMaxs[i][0] = minsAndMaxs[i][0];
newMinsAndMaxs[i][1] = minsAndMaxs[i][1];
if (i == m_attIndex)
if (data.attribute(m_attIndex).Nominal)
newMinsAndMaxs[m_attIndex][1] = 1;
else
newMinsAndMaxs[m_attIndex][1 - index] = m_splitPoint;
}
return newMinsAndMaxs;
}
示例4: sourceExpression
/// <summary> Returns a string containing java source code equivalent to the test
/// made at this node. The instance being tested is called "i".
///
/// </summary>
/// <param name="index">index of the nominal value tested
/// </param>
/// <param name="data">the data containing instance structure info
/// </param>
/// <returns> a value of type 'String'
/// </returns>
public override System.String sourceExpression(int index, Instances data)
{
System.Text.StringBuilder expr = null;
if (index < 0)
{
return "i[" + m_attIndex + "] == null";
}
if (data.attribute(m_attIndex).Nominal)
{
expr = new System.Text.StringBuilder("i[");
expr.Append(m_attIndex).Append("]");
expr.Append(".equals(\"").Append(data.attribute(m_attIndex).value_Renamed(index)).Append("\")");
}
else
{
expr = new System.Text.StringBuilder("((Double) i[");
expr.Append(m_attIndex).Append("])");
if (index == 0)
{
expr.Append(".doubleValue() <= ").Append(m_splitPoint);
}
else
{
expr.Append(".doubleValue() > ").Append(m_splitPoint);
}
}
return expr.ToString();
}
示例5: rightSide
/// <summary> Prints the condition satisfied by instances in a subset.
///
/// </summary>
/// <param name="index">of subset
/// </param>
/// <param name="data">training set.
/// </param>
public override System.String rightSide(int index, Instances data)
{
System.Text.StringBuilder text;
text = new System.Text.StringBuilder();
if (data.attribute(m_attIndex).Nominal)
text.Append(" = " + data.attribute(m_attIndex).value_Renamed(index));
else if (index == 0)
text.Append(" <= " + Utils.doubleToString(m_splitPoint, 6));
else
text.Append(" > " + Utils.doubleToString(m_splitPoint, 6));
return text.ToString();
}
示例6: leftSide
/// <summary> Prints left side of condition..
///
/// </summary>
/// <param name="data">training set.
/// </param>
public override System.String leftSide(Instances data)
{
return data.attribute(m_attIndex).name();
}
示例7: buildClassifier
/// <summary> Creates a C4.5-type split on the given data. Assumes that none of
/// the class values is missing.
///
/// </summary>
/// <exception cref="Exception">if something goes wrong
/// </exception>
public override void buildClassifier(Instances trainInstances)
{
// Initialize the remaining instance variables.
m_numSubsets = 0;
//UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
m_splitPoint = System.Double.MaxValue;
m_infoGain = 0;
m_gainRatio = 0;
// Different treatment for enumerated and numeric
// attributes.
if (trainInstances.attribute(m_attIndex).Nominal)
{
m_complexityIndex = trainInstances.attribute(m_attIndex).numValues();
m_index = m_complexityIndex;
handleEnumeratedAttribute(trainInstances);
}
else
{
m_complexityIndex = 2;
m_index = 0;
trainInstances.sort(trainInstances.attribute(m_attIndex));
handleNumericAttribute(trainInstances);
}
}
示例8: MITesDataCollectionForm
public MITesDataCollectionForm(string dataDirectory, string arffFile, bool isHierarchical)
{
//where data is being stored
this.dataDirectory = dataDirectory;
//Initialize high resolution unix timer
UnixTime.InitializeTime();
//Initialize and start GUI progress thread
progressMessage = null;
aProgressThread = new Thread(new ThreadStart(ProgressThread));
aProgressThread.Start();
#region Load Configuration files
//load the activity and sensor configuration files
progressMessage = "Loading XML protocol and sensors ...";
AXML.Reader reader = new AXML.Reader(Constants.MASTER_DIRECTORY, dataDirectory);
#if (!PocketPC)
if (reader.validate() == false)
{
throw new Exception("Error Code 0: XML format error - activities.xml does not match activities.xsd!");
}
else
{
#endif
this.annotation = reader.parse();
this.annotation.DataDirectory = dataDirectory;
SXML.Reader sreader = new SXML.Reader(Constants.MASTER_DIRECTORY, dataDirectory);
#if (!PocketPC)
if (sreader.validate() == false)
{
throw new Exception("Error Code 0: XML format error - sensors.xml does not match sensors.xsd!");
}
else
{
#endif
this.sensors = sreader.parse(Constants.MAX_CONTROLLERS);
progressMessage += " Completed\r\n";
//TODO: remove BT components
progressMessage += "Loading configuration file ...";
MITesFeatures.core.conf.ConfigurationReader creader = new MITesFeatures.core.conf.ConfigurationReader(dataDirectory);
this.configuration = creader.parse();
progressMessage += " Completed\r\n";
#if (!PocketPC)
}
}
#endif
#endregion Load Configuration files
#region Initialize External Data Reception Channels
//Initialize 1 master decoder
this.masterDecoder = new MITesDecoder();
//Initialize the software mode
isExtracting = false;
isCollectingDetailedData = false;
isPlotting = true;
isClassifying = true;
#region Initialize Feature Extraction
this.isExtracting = false;
if (this.sensors.TotalReceivers > 0) // if there is at least 1 MIT
//Extractor.Initialize(this.mitesDecoders[0], dataDirectory, this.annotation, this.sensors, this.configuration);
Extractor.Initialize(this.masterDecoder, dataDirectory, this.annotation, this.sensors, this.configuration);
else if (this.sensors.Sensors.Count > 0) // only built in
Extractor.Initialize(this.masterDecoder, dataDirectory, this.annotation, this.sensors, this.configuration);
#endregion Initialize Feature Extraction
labelIndex = new Hashtable();
instances = new Instances(new StreamReader(arffFile));
instances.Class = instances.attribute(Extractor.ArffAttributeLabels.Length);
classifier = new J48();
if (!File.Exists("model.xml"))
{
classifier.buildClassifier(instances);
TextWriter tc = new StreamWriter("model.xml");
classifier.toXML(tc);
tc.Flush();
tc.Close();
}
else
classifier.buildClassifier("model.xml", instances);
fvWekaAttributes = new FastVector(Extractor.ArffAttributeLabels.Length + 1);
for (int i = 0; (i < Extractor.ArffAttributeLabels.Length); i++)
fvWekaAttributes.addElement(new weka.core.Attribute(Extractor.ArffAttributeLabels[i]));
FastVector fvClassVal = new FastVector();
labelCounters = new int[((AXML.Category)this.annotation.Categories[0]).Labels.Count + 1];
activityLabels = new string[((AXML.Category)this.annotation.Categories[0]).Labels.Count + 1];
//.........这里部分代码省略.........
示例9: rightSide
/// <summary> Prints the condition satisfied by instances in a subset.
///
/// </summary>
/// <param name="index">of subset and training set.
/// </param>
public override System.String rightSide(int index, Instances data)
{
System.Text.StringBuilder text;
text = new System.Text.StringBuilder();
if (data.attribute(m_attIndex).Nominal)
{
if (index == 0)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
text.Append(" = " + data.attribute(m_attIndex).value_Renamed((int) m_splitPoint));
}
else
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
text.Append(" != " + data.attribute(m_attIndex).value_Renamed((int) m_splitPoint));
}
}
else if (index == 0)
text.Append(" <= " + m_splitPoint);
else
text.Append(" > " + m_splitPoint);
return text.ToString();
}
示例10: handleEnumeratedAttribute
/// <summary> Creates split on enumerated attribute.
///
/// </summary>
/// <exception cref="Exception">if something goes wrong
/// </exception>
private void handleEnumeratedAttribute(Instances trainInstances)
{
Distribution newDistribution, secondDistribution;
int numAttValues;
double currIG, currGR;
Instance instance;
int i;
numAttValues = trainInstances.attribute(m_attIndex).numValues();
newDistribution = new Distribution(numAttValues, trainInstances.numClasses());
// Only Instances with known values are relevant.
System.Collections.IEnumerator enu = trainInstances.enumerateInstances();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (enu.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
instance = (Instance) enu.Current;
if (!instance.isMissing(m_attIndex))
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
newDistribution.add((int) instance.value_Renamed(m_attIndex), instance);
}
}
m_distribution = newDistribution;
// For all values
for (i = 0; i < numAttValues; i++)
{
if (Utils.grOrEq(newDistribution.perBag(i), m_minNoObj))
{
secondDistribution = new Distribution(newDistribution, i);
// Check if minimum number of Instances in the two
// subsets.
if (secondDistribution.check(m_minNoObj))
{
m_numSubsets = 2;
currIG = m_infoGainCrit.splitCritValue(secondDistribution, m_sumOfWeights);
currGR = m_gainRatioCrit.splitCritValue(secondDistribution, m_sumOfWeights, currIG);
if ((i == 0) || Utils.gr(currGR, m_gainRatio))
{
m_gainRatio = currGR;
m_infoGain = currIG;
m_splitPoint = (double) i;
m_distribution = secondDistribution;
}
}
}
}
}
示例11: PerformTraining
//.........这里部分代码省略.........
//((IBk)this.CurrentClassifier).setKNN((int)Parameters.ListDoubleValues.Get("numericUpDownKNN").Value);
this.CurrentClassifier.buildClassifier(train);
}
#endregion
#region Multilayer Perceptron
else if (ClassifAlgoParams.Name == "Perceptron")
{
this.CurrentClassifier = new weka.classifiers.functions.MultilayerPerceptron();
((MultilayerPerceptron)this.CurrentClassifier).setMomentum((double)Parameters.ListDoubleValues.Get("numericUpDownMomentum").Value);
((MultilayerPerceptron)this.CurrentClassifier).setLearningRate((double)Parameters.ListDoubleValues.Get("numericUpDownLearningRate").Value);
((MultilayerPerceptron)this.CurrentClassifier).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeed").Value);
((MultilayerPerceptron)this.CurrentClassifier).setTrainingTime((int)Parameters.ListDoubleValues.Get("numericUpDownTrainingTime").Value);
((MultilayerPerceptron)this.CurrentClassifier).setNormalizeAttributes((bool)Parameters.ListCheckValues.Get("checkBoxNormAttribute").Value);
((MultilayerPerceptron)this.CurrentClassifier).setNormalizeNumericClass((bool)Parameters.ListCheckValues.Get("checkBoxNormNumericClasses").Value);
this.CurrentClassifier.buildClassifier(train);
}
#endregion
#region ZeroR
else if (ClassifAlgoParams.Name == "ZeroR")
{
this.CurrentClassifier = new weka.classifiers.rules.OneR();
this.CurrentClassifier.buildClassifier(train);
}
#endregion
#region OneR
else if (ClassifAlgoParams.Name == "OneR")
{
this.CurrentClassifier = new weka.classifiers.rules.OneR();
((OneR)this.CurrentClassifier).setMinBucketSize((int)Parameters.ListDoubleValues.Get("numericUpDownMinBucketSize").Value);
this.CurrentClassifier.buildClassifier(train);
}
#endregion
#region Naive Bayes
else if (ClassifAlgoParams.Name == "NaiveBayes")
{
this.CurrentClassifier = new weka.classifiers.bayes.NaiveBayes();
((NaiveBayes)this.CurrentClassifier).setUseKernelEstimator((bool)Parameters.ListCheckValues.Get("checkBoxKernelEstimator").Value);
this.CurrentClassifier.buildClassifier(train);
}
#endregion
#region Logistic
else if (ClassifAlgoParams.Name == "Logistic")
{
this.CurrentClassifier = new weka.classifiers.functions.Logistic();
((Logistic)this.CurrentClassifier).setUseConjugateGradientDescent((bool)Parameters.ListCheckValues.Get("checkBoxUseConjugateGradientDescent").Value);
((Logistic)this.CurrentClassifier).setRidge((double)Parameters.ListDoubleValues.Get("numericUpDownRidge").Value);
this.CurrentClassifier.buildClassifier(train);
}
#endregion
//weka.classifiers.functions.SMO
//BayesNet
#endregion
if (TextBoxForFeedback != null)
{
TextBoxForFeedback.Clear();
TextBoxForFeedback.AppendText(this.CurrentClassifier.ToString());
}
TextBoxForFeedback.AppendText("\n" + (InstancesList.numAttributes() - 1) + " attributes:\n\n");
for (int IdxAttributes = 0; IdxAttributes < InstancesList.numAttributes() - 1; IdxAttributes++)
{
TextBoxForFeedback.AppendText(IdxAttributes + "\t: " + InstancesList.attribute(IdxAttributes).name() + "\n");
}
#region evaluation of the model and results display
if ((WindowForClassificationParam.numericUpDownFoldNumber.Enabled) && (TextBoxForFeedback != null))
{
TextBoxForFeedback.AppendText("\n-----------------------------\nModel validation\n-----------------------------\n");
ModelEvaluation = new weka.classifiers.Evaluation(InstancesList);
ModelEvaluation.crossValidateModel(this.CurrentClassifier, InstancesList, (int)WindowForClassificationParam.numericUpDownFoldNumber.Value, new java.util.Random(1));
TextBoxForFeedback.AppendText(ModelEvaluation.toSummaryString());
TextBoxForFeedback.AppendText("\n-----------------------------\nConfusion Matrix:\n-----------------------------\n");
double[][] ConfusionMatrix = ModelEvaluation.confusionMatrix();
string NewLine = "";
for (int i = 0; i < ConfusionMatrix[0].Length; i++)
{
NewLine += "c" + i + "\t";
}
TextBoxForFeedback.AppendText(NewLine + "\n\n");
for (int j = 0; j < ConfusionMatrix.Length; j++)
{
NewLine = "";
for (int i = 0; i < ConfusionMatrix[0].Length; i++)
{
NewLine += ConfusionMatrix[j][i] + "\t";
}
// if
TextBoxForFeedback.AppendText(NewLine + "| c" + j + " <=> " + cGlobalInfo.ListCellularPhenotypes[j].Name + "\n");
}
}
#endregion
return this.CurrentClassifier;
}
示例12: EvaluteAndDisplayClusterer
/// <summary>
/// Evalute and display a WEKA clusterer
/// </summary>
/// <param name="SelectedClusterer">weka clusterer</param>
/// <param name="InstancesList">list of instances for the validation</param>
/// <param name="RichTextBoxToDisplayResults">Text box for the results (can be NULL)</param>
/// <param name="PanelTodisplayGraphicalResults">Panel to display visual results if avalaible (can be NULL)</param>
/// <returns></returns>
public ClusterEvaluation EvaluteAndDisplayClusterer(RichTextBox RichTextBoxToDisplayResults,
Panel PanelTodisplayGraphicalResults, Instances ListInstanceForValid)
{
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(SelectedClusterer);
eval.evaluateClusterer(ListInstanceForValid);
if (RichTextBoxToDisplayResults != null)
{
if ((RichTextBoxToDisplayResults != null) && (eval.getNumClusters() > cGlobalInfo.ListCellularPhenotypes.Count))
{
RichTextBoxToDisplayResults.Clear();
RichTextBoxToDisplayResults.AppendText("Error: " + eval.getNumClusters() + " clusters identifed.");
RichTextBoxToDisplayResults.AppendText("The maximum number of cluster is " + cGlobalInfo.ListCellularPhenotypes.Count + ".");
return null;
}
if (RichTextBoxToDisplayResults != null)
{
RichTextBoxToDisplayResults.Clear();
RichTextBoxToDisplayResults.AppendText(eval.clusterResultsToString());
}
RichTextBoxToDisplayResults.AppendText("\n" + ListInstanceForValid.numAttributes() + " attributes:\n\n");
for (int IdxAttributes = 0; IdxAttributes < ListInstanceForValid.numAttributes(); IdxAttributes++)
{
RichTextBoxToDisplayResults.AppendText(IdxAttributes + "\t: " + ListInstanceForValid.attribute(IdxAttributes).name() + "\n");
}
}
if (PanelTodisplayGraphicalResults != null) PanelTodisplayGraphicalResults.Controls.Clear();
if ((PanelTodisplayGraphicalResults != null) && (SelectedClusterer.GetType().Name == "HierarchicalClusterer"))
{
Button ButtonToDisplayHierarchicalClustering = new Button();
ButtonToDisplayHierarchicalClustering.Text = "Display Hierarchical Tree";
ButtonToDisplayHierarchicalClustering.Width *= 2;
ButtonToDisplayHierarchicalClustering.Location = new System.Drawing.Point((PanelTodisplayGraphicalResults.Width - ButtonToDisplayHierarchicalClustering.Width) / 2,
(PanelTodisplayGraphicalResults.Height - ButtonToDisplayHierarchicalClustering.Height) / 2);
ButtonToDisplayHierarchicalClustering.Anchor = AnchorStyles.None;
ButtonToDisplayHierarchicalClustering.Click += new EventHandler(ClickToDisplayHierarchicalTree);
PanelTodisplayGraphicalResults.Controls.Add(ButtonToDisplayHierarchicalClustering);
}
return eval;
}
示例13: setInputFormat
// ---- OPERATIONS ----
///
/// <summary> * Sets the format of the input instances. If the filter is able to
/// * determine the output format before seeing any input instances, it
/// * does so here. This default implementation clears the output format
/// * and output queue, and the new batch flag is set. Overriders should
/// * call <code>super.setInputFormat(Instances)</code>
/// * </summary>
/// * <param name="instanceInfo"> an Instances object containing the input instance
/// * structure (any instances contained in the object are ignored - only the
/// * structure is required). </param>
/// * <returns> true if the outputFormat may be collected immediately </returns>
/// * <exception cref="Exception"> if the inputFormat can't be set successfully </exception>
///
//JAVA TO VB & C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public boolean setInputFormat(Instances instanceInfo) throws Exception
public override bool setInputFormat(Instances instanceInfo)
{
base.setInputFormat(instanceInfo);
for (int i = 0; i < instanceInfo.numAttributes(); ++i)
{
if (!instanceInfo.attribute(i).isNumeric())
{
throw new UnsupportedAttributeTypeException("All attributes must be numeric");
}
}
// Create the output buffer
setOutputFormat();
return true;
}
示例14: equalHeaders
/// <summary> Checks if two headers are equivalent.
///
/// </summary>
/// <param name="dataset">another dataset
/// </param>
/// <returns> true if the header of the given dataset is equivalent
/// to this header
/// </returns>
public virtual bool equalHeaders(Instances dataset)
{
// Check class and all attributes
if (m_ClassIndex != dataset.m_ClassIndex)
{
return false;
}
if (m_Attributes.size() != dataset.m_Attributes.size())
{
return false;
}
for (int i = 0; i < m_Attributes.size(); i++)
{
if (!(attribute(i).Equals(dataset.attribute(i))))
{
return false;
}
}
return true;
}
示例15: mergeInstances
/// <summary> Merges two sets of Instances together. The resulting set will have
/// all the attributes of the first set plus all the attributes of the
/// second set. The number of instances in both sets must be the same.
///
/// </summary>
/// <param name="first">the first set of Instances
/// </param>
/// <param name="second">the second set of Instances
/// </param>
/// <returns> the merged set of Instances
/// </returns>
/// <exception cref="IllegalArgumentException">if the datasets are not the same size
/// </exception>
public static Instances mergeInstances(Instances first, Instances second)
{
if (first.numInstances() != second.numInstances())
{
throw new System.ArgumentException("Instance sets must be of the same size");
}
// Create the vector of merged attributes
FastVector newAttributes = new FastVector();
for (int i = 0; i < first.numAttributes(); i++)
{
newAttributes.addElement(first.attribute(i));
}
for (int i = 0; i < second.numAttributes(); i++)
{
newAttributes.addElement(second.attribute(i));
}
// Create the set of Instances
Instances merged = new Instances(first.relationName() + '_' + second.relationName(), newAttributes, first.numInstances());
// Merge each instance
for (int i = 0; i < first.numInstances(); i++)
{
merged.add(first.instance(i).mergeInstance(second.instance(i)));
}
return merged;
}