Esempio n. 1
0
        private static void Main()
        {
            // Create random data
            var       r          = new Random();
            const int trainCount = 500;
            const int testCount  = 100;

            var temp       = Path.GetTempPath();
            var trainDic   = new StringBuilder();
            var testDic    = new StringBuilder();
            var testDicAns = new List <int>();

            for (var l = 0; l < 10; l++)
            {
                for (var i = 0; i < trainCount; i++)
                {
                    // Create decimal value 0 or greater but less than 10
                    var v = r.NextDouble() + l;
                    trainDic.AppendLine($"{l} 1:{v}");
                }
                for (var i = 0; i < testCount; i++)
                {
                    // Create decimal value 0 or greater but less than 10
                    var v = r.NextDouble() + l;
                    testDic.AppendLine($"{l} 1:{v}");
                    testDicAns.Add(l);
                }
            }

            var tempTrainPath = Path.Combine(temp, "train");
            var tempTestPath  = Path.Combine(temp, "test");

            using (var fs = new FileStream(tempTrainPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                using (var sw = new StreamWriter(fs, Encoding.ASCII))
                    sw.Write(trainDic.ToString());

            using (var fs = new FileStream(tempTestPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                using (var sw = new StreamWriter(fs, Encoding.ASCII))
                    sw.Write(testDic.ToString());

            // Load training data and test data set
            using (var train = Problem.FromFile(tempTrainPath))
                using (var test = Problem.FromFile(tempTestPath))
                {
                    // Configure parameter
                    var param = new Parameter
                    {
                        SvmType     = SvmType.CSVC,
                        KernelType  = KernelType.RBF,
                        Gamma       = 0.05d,
                        C           = 5d,
                        CacheSize   = 100,
                        Degree      = 3,
                        Coef0       = 0,
                        Nu          = 0.5,
                        Epsilon     = 1e-3,
                        P           = 0.1,
                        Shrinking   = true,
                        Probability = false,
                        WeightLabel = new int[0],
                        Weight      = new double[0]
                    };

                    var message = LibSvm.CheckParameter(train, param);
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        Console.WriteLine($"Error: {message} for train problem");
                        return;
                    }

                    message = LibSvm.CheckParameter(test, param);
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        Console.WriteLine($"Error: {message} for test problem");
                        return;
                    }

                    // Train training data
                    using (var model = LibSvm.Train(train, param))
                    {
                        var correct = 0;
                        var total   = 0;
                        var x       = test.X;
                        for (var i = 0; i < test.Length; i++)
                        {
                            // Get vector from test data
                            var array = x[i];

                            // Get classification result (returns label)
                            var ret1 = (int)LibSvm.Predict(model, array);
                            if (ret1 == testDicAns[i])
                            {
                                correct++;
                            }

                            total++;
                        }

                        Console.WriteLine($"Accuracy: {correct / (double)total * 100}%");
                    }
                }
        }
Esempio n. 2
0
        private static void Main(string[] args)
        {
            var app = new CommandLineApplication(false);

            app.Name        = nameof(CrossValidation);
            app.Description = "The exsample program for cross validation";
            app.HelpOption("-h|--help");

            var quietArgument = app.Argument("quiet", "Suppress output of LIBSVM");
            var foldOption    = app.Option("-f|--fold", "K-fold. (An integer of not less than 0)", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                if (quietArgument.Value != null)
                {
                    LibSvm.SetPrintFunction(null);
                }

                if (!foldOption.HasValue())
                {
                    app.ShowHelp();
                    return(-1);
                }

                if (!int.TryParse(foldOption.Value(), out var fold))
                {
                    app.ShowHelp();
                    return(-1);
                }

                // Create random data
                var r = new Random();
                const int trainCount = 500;

                var temp     = Path.GetTempPath();
                var trainDic = new StringBuilder();

                for (var l = 0; l < 10; l++)
                {
                    for (var i = 0; i < trainCount; i++)
                    {
                        // Create decimal value 0 or greater but less than 10
                        var v = r.NextDouble() + l;
                        trainDic.AppendLine($"{l} 1:{v}");
                    }
                }

                var tempTrainPath = Path.Combine(temp, "train");

                using (var fs = new FileStream(tempTrainPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                    using (var sw = new StreamWriter(fs, Encoding.ASCII))
                        sw.Write(trainDic.ToString());

                // Load training data and test data set
                using (var train = Problem.FromFile(tempTrainPath))
                {
                    // Configure parameter
                    var param = new Parameter
                    {
                        SvmType     = SvmType.CSVC,
                        KernelType  = KernelType.RBF,
                        Gamma       = 0.05d,
                        C           = 5d,
                        CacheSize   = 100,
                        Degree      = 3,
                        Coef0       = 0,
                        Nu          = 0.5,
                        Epsilon     = 1e-3,
                        P           = 0.1,
                        Shrinking   = true,
                        Probability = false,
                        WeightLabel = new int[0],
                        Weight      = new double[0]
                    };

                    var message = LibSvm.CheckParameter(train, param);
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        Console.WriteLine($"Error: {message} for train problem");
                        return(-1);
                    }

                    // Do cross validation
                    LibSvm.CrossValidation(train, param, fold, out var target);

                    var correct = 0;
                    var total   = 0;
                    var y       = train.Y;
                    for (var i = 0; i < train.Length; i++)
                    {
                        // Compare predict result and train data label
                        if ((int)y[i] == (int)target[i])
                        {
                            correct++;
                        }

                        total++;
                    }

                    Console.WriteLine($"Accuracy: {correct / (double)total * 100}%");
                }

                return(0);
            });

            app.Execute(args);
        }
Esempio n. 3
0
        private static void Main(string[] args)
        {
            var app = new CommandLineApplication(false);

            app.Name        = nameof(MNIST);
            app.Description = "The exsample program for MNIST";
            app.HelpOption("-h|--help");

            var quietArgument = app.Argument("quiet", "Suppress output of LIBSVM");
            var outputOption  = app.Option("-o|--output", "output path for trained model", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                if (quietArgument.Value != null)
                {
                    LibSvm.SetPrintFunction(null);
                }

                var output = outputOption.Value();

                // Load training data and test data set
                using (var train = Problem.FromFile("mnist"))
                    using (var test = Problem.FromFile("mnist.t"))
                    {
                        // Configure parameter
                        var param = new Parameter
                        {
                            SvmType     = SvmType.CSVC,
                            KernelType  = KernelType.Linear,
                            Gamma       = 0.05d,
                            C           = 5d,
                            CacheSize   = 1000,
                            Degree      = 3,
                            Coef0       = 0,
                            Nu          = 0.5,
                            Epsilon     = 1e-3,
                            P           = 0.1,
                            Shrinking   = true,
                            Probability = false,
                            WeightLabel = new int[0],
                            Weight      = new double[0]
                        };

                        var message = LibSvm.CheckParameter(train, param);
                        if (!string.IsNullOrWhiteSpace(message))
                        {
                            Console.WriteLine($"Error: {message} for train problem");
                            return(-1);
                        }

                        // Train training data
                        var sw = new Stopwatch();
                        sw.Start();
                        using (var model = LibSvm.Train(train, param))
                        {
                            sw.Stop();

                            if (!string.IsNullOrWhiteSpace(output))
                            {
                                Model.Save(output, model);
                            }

                            var correct = 0;
                            var total   = 0;
                            var x       = test.X;
                            var y       = test.Y;
                            for (var i = 0; i < test.Length; i++)
                            {
                                // Get vector from test data
                                var array = x[i];

                                // Get classification result (returns label)
                                var ret1 = (int)LibSvm.Predict(model, array);
                                if (ret1 == (int)y[i])
                                {
                                    correct++;
                                }

                                total++;
                            }

                            Console.WriteLine($"Accuracy: {correct / (double)total * 100}%, Elapsed: {sw.ElapsedMilliseconds / 1000}s");
                        }
                    }

                return(0);
            });

            app.Execute(args);
        }
Esempio n. 4
0
        private static void Main()
        {
            // Create random data
            var       r          = new Random();
            const int trainCount = 500;
            const int testCount  = 100;

            var trainNodes  = new List <Node[]>();
            var trainLabels = new List <double>();
            var testNodes   = new List <Node[]>();
            var testLabels  = new List <double>();

            for (var l = 0; l < 2; l++)
            {
                for (var i = 0; i < trainCount; i++)
                {
                    // Create decimal value 0 or greater but less than 2
                    var v = r.NextDouble() + l;
                    trainNodes.Add(new[] { new Node {
                                               Index = 0, Value = v
                                           } });
                    trainLabels.Add(l);
                }
                for (var i = 0; i < testCount; i++)
                {
                    // Create decimal value 0 or greater but less than 2
                    var v = r.NextDouble() + l;
                    testNodes.Add(new[] { new Node {
                                              Index = 0, Value = v
                                          } });
                    testLabels.Add(l);
                }
            }

            // Load training data and test data set
            using (var train = Problem.FromSequence(trainNodes, trainLabels))
                using (var test = Problem.FromSequence(testNodes, testLabels))
                {
                    // Configure parameter
                    var param = new Parameter
                    {
                        SvmType     = SvmType.CSVC,
                        KernelType  = KernelType.RBF,
                        Gamma       = 0.05d,
                        C           = 5d,
                        CacheSize   = 100,
                        Degree      = 3,
                        Coef0       = 0,
                        Nu          = 0.5,
                        Epsilon     = 1e-3,
                        P           = 0.1,
                        Shrinking   = true,
                        Probability = false,
                        WeightLabel = new int[0],
                        Weight      = new double[0]
                    };

                    var message = LibSvm.CheckParameter(train, param);
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        Console.WriteLine($"Error: {message} for train problem");
                        return;
                    }

                    message = LibSvm.CheckParameter(test, param);
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        Console.WriteLine($"Error: {message} for test problem");
                        return;
                    }

                    // Train training data
                    using (var model = LibSvm.Train(train, param))
                    {
                        var correct = 0;
                        var total   = 0;
                        var x       = test.X;
                        for (var i = 0; i < test.Length; i++)
                        {
                            // Get vector from test data
                            var array = x[i];

                            // Get classification result (returns label)
                            var ret1 = (int)LibSvm.Predict(model, array);
                            if (ret1 == (int)testLabels[i])
                            {
                                correct++;
                            }

                            total++;
                        }

                        Console.WriteLine($"Accuracy: {correct / (double)total * 100}%");
                    }
                }
        }