Simple Accord.NET Machine Learning Example
Introduction
Accord.NET is a powerful open-source framework for machine learning and scientific computing in .NET. This example demonstrates a basic classification task using Accord.NET’s decision tree classifier.
Requirements
* Visual Studio or another .NET IDE * Accord.NET NuGet package
Code
“`csharp using Accord.MachineLearning; using Accord.MachineLearning.DecisionTrees; using Accord.Math.Distances; public class DecisionTreeExample { public static void Main(string[] args) { // Define input data double[][] inputs = { new double[] { 1, 0, 0 }, // Class 0 new double[] { 1, 1, 0 }, // Class 1 new double[] { 0, 0, 1 }, // Class 0 new double[] { 0, 1, 1 } // Class 1 }; // Define output labels int[] outputs = { 0, 1, 0, 1 }; // Create a decision tree classifier DecisionTree tree = new DecisionTree( new EuclideanDistance(), // Distance metric new InformationGainSplitCriterion() // Split criterion ); // Train the decision tree tree.Learn(inputs, outputs); // Predict the class of a new instance double[] newInstance = { 1, 0, 1 }; int predictedClass = tree.Decide(newInstance); // Print the predicted class Console.WriteLine($”Predicted class: {predictedClass}”); } } “`
Explanation
1. **Import namespaces:** We start by importing necessary namespaces for machine learning and decision trees. 2. **Input and Output Data:** Define input data (features) as a 2D array `inputs` and output labels (classes) as an array `outputs`. 3. **Create a Decision Tree:** We instantiate a `DecisionTree` object, specifying a distance metric (Euclidean) and a split criterion (information gain). 4. **Train the Decision Tree:** The `Learn` method trains the decision tree based on the input and output data. 5. **Predict New Instance:** A new input instance `newInstance` is provided, and the `Decide` method predicts its class. 6. **Print Prediction:** The predicted class is printed to the console.
Output
“` Predicted class: 0 “`
Conclusion
This simple example showcases how to use Accord.NET’s decision tree classifier for a basic classification task. It demonstrates the key steps: data preparation, model creation, training, and prediction. Accord.NET offers a wide range of machine learning algorithms and tools for more complex applications.