我想将动态时间规整和支持向量机结合起来用作分类器。我使用的是 Accord .net,但我的代码似乎有些问题,以下是我的代码:
double[][] inputs = new double[100][]; for(int i = 0; i < linesX.Length; i++) { inputs[i] = Array.ConvertAll(linesX[i].Split(','), Double.Parse); } int[] outputs = Array.ConvertAll(linesY, s => int.Parse(s)); // 创建顺序最小优化学习算法 var smo = new MulticlassSupportVectorLearning<DynamicTimeWarping>() { // 设置核函数的参数 Kernel = new DynamicTimeWarping(alpha: 1, degree: 1) }; // 使用它来学习一个机器! var svm = smo.Learn(inputs, outputs); // 现在我们可以计算预测值 int[] predicted = svm.Decide(inputs); // 并检查与预期值的差距 double error = new ZeroOneLoss(outputs).Loss(predicted);
我的输入是 (100,800),输出是 (100,1),在这一行会出现异常:var svm = smo.Learn(inputs, outputs);
异常是 “System.AggregateException” 发生在 Accord.MachineLearning.dll
我的代码哪里出了问题?
回答:
请参考正确的设置 这里。你没有分配 Learner
属性。
这是我修改后的代码,包含了一些随机输入数据:
static void Main(string[] args) { Random r = new Random(); double[][] inputs = new double[10][]; int[] outputs = new int[10]; for (int i = 0; i < 10; i++) { inputs[i] = new double[8]; for (int j = 0; j < 8; j++) { inputs[i][j] = r.Next(1, 100); } outputs[i] = r.Next(1, 6); } var smo = new MulticlassSupportVectorLearning<DynamicTimeWarping>() { Learner = (param) => new SequentialMinimalOptimization<DynamicTimeWarping>() { Kernel = new DynamicTimeWarping(alpha: 1, degree: 1), } }; var svm = smo.Learn(inputs, outputs); int[] predicted = svm.Decide(inputs); double error = new ZeroOneLoss(outputs).Loss(predicted); Console.WriteLine(); Console.WriteLine("output = \n{0}", Matrix.ToString(outputs)); Console.WriteLine(); Console.WriteLine("predicted = \n{0}", Matrix.ToString(predicted)); Console.WriteLine(); Console.WriteLine("error = {0}", error); Console.ReadLine(); }
这将产生类似这样的结果:
output =2 3 1 2 1 2 2 3 5 1predicted =2 1 1 2 1 2 2 2 2 1error = 0.3