Accord.Net之HelloWorld(1)
阿新 • • 發佈:2018-11-14
開發環境配置
1.本系列博文主要以VS2017版本介紹,具體安裝方法請參照官方說明;
2.模組的引用請參照上一小結;
建立新專案
本章節將從啟動Visual Studio開始,逐步介紹開發如何使用Accord.Net開發一個簡單的事例,以決策樹分類為例。
Visual啟動後,選擇【檔案】->【新建專案】
在彈出的新建對話方塊中,以Visual C#分類下選擇【控制檯應用程式】。在本章節中雖然建立的事例是C#語言,但Accord.Net同樣支援所有.Net相容的語言,如VB.Net或C++/CLI。
給新建的專案新增引用。具體操作可參考上一節介紹的兩種方法,在這裡通過命令的方式添加了Accord.MachineLearning模組。
PM>Install-Package Accord.MachineLearning
編碼
現在準備開發應用程式。下面將演示如何建立和訓練一個決策樹模型識別一個西瓜是否為好瓜,關於決策樹的相關介紹大家可以看看周志華的《機器學習》一書,在這裡就不在累贅相關的原理。問題關鍵在學習下面的訓練集:
編號(No) |
Color(色澤) | Root(根蒂) | Sound(敲聲) | Result(好瓜) |
---|---|---|---|---|
1 |
青綠 | 蜷縮 | 濁響 | 是 |
2 |
烏黑 | 蜷縮 | 濁響 | 是 |
3 |
青綠 | 硬挺 | 清脆 | 否 |
4 |
烏黑 | 稍蜷 | 沉悶 | 否 |
輸入資料集inputs由Color、Root、Sound、Good三列組成,對應的輸出資料集output由Result組成,在這裡主要採用C45方法進行訓練,關鍵程式碼如下:
//1.建立資料集 DataTable data = new DataTable("Watermelon Example"); data.Columns.Add("No", typeof(string)); data.Columns.Add("Color", typeof(string)); data.Columns.Add("Root", typeof(string)); data.Columns.Add("Sound", typeof(string)); data.Columns.Add("Result", typeof(string)); data.Rows.Add("1", "青綠", "蜷縮", "濁響", "是"); data.Rows.Add("2", "烏黑", "蜷縮", "濁響", "是"); data.Rows.Add("3", "青綠", "硬挺", "清脆", "否"); data.Rows.Add("4", "烏黑", "稍蜷", "沉悶", "否"); data.Rows.Add("5", "青綠", "蜷縮", "濁響", "是");//用於預測 //2.建立Codification用於把字串轉化為整型 Codification codebook = new Codification(data); DecisionVariable[] attributes = { new DecisionVariable("Color",codebook["Color"].NumberOfClasses), new DecisionVariable("Root",codebook["Root"].NumberOfClasses), new DecisionVariable("Sound",codebook["Outlook"].NumberOfClasses) }; int classCount = codebook["Result"].NumberOfClasses; //3.建立C45決策樹 tree = new DecisionTree(attributes, classCount); C45Learning c45 = new C45Learning(tree); DataTable symbols = codebook.Apply(data); inputs = symbols.ToJagged("Color", "Root", "Sound"); outputs = symbols.ToArray<int>("Result"); c45.Learn(inputs, outputs);
測試程式碼:
static void Main(string[] args)
{
DecisionTree tree;
double[][] inputs;
int[] outputs;
CreateDecisionTreeExample(out tree, out inputs, out outputs);
int result = tree.Decide(inputs[4]);
Console.WriteLine("該瓜是否是好瓜:" + (result == 0 ? "是" : "否"));
Console.ReadKey();
}
執行結果如圖所示