• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# SVM.Problem类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中SVM.Problem的典型用法代码示例。如果您正苦于以下问题:C# Problem类的具体用法?C# Problem怎么用?C# Problem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Problem类属于SVM命名空间,在下文中一共展示了Problem类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Compute

        /// <summary>
        /// Determines the Gaussian transform for the provided problem.
        /// </summary>
        /// <param name="prob">The Problem to analyze</param>
        /// <returns>The Gaussian transform for the problem</returns>
        public static GaussianTransform Compute(Problem prob)
        {
            int[] counts = new int[prob.MaxIndex];
              double[] means = new double[prob.MaxIndex];
              foreach (Node[] sample in prob.X) {
            for (int i = 0; i < sample.Length; i++) {
              means[sample[i].Index - 1] += sample[i].Value;
              counts[sample[i].Index - 1]++;
            }
              }
              for (int i = 0; i < prob.MaxIndex; i++) {
            if (counts[i] == 0)
              counts[i] = 2;
            means[i] /= counts[i];
              }

              double[] stddevs = new double[prob.MaxIndex];
              foreach (Node[] sample in prob.X) {
            for (int i = 0; i < sample.Length; i++) {
              double diff = sample[i].Value - means[sample[i].Index - 1];
              stddevs[sample[i].Index - 1] += diff * diff;
            }
              }
              for (int i = 0; i < prob.MaxIndex; i++) {
            if (stddevs[i] == 0)
              continue;
            stddevs[i] /= (counts[i] - 1);
            stddevs[i] = Math.Sqrt(stddevs[i]);
              }

              return new GaussianTransform(means, stddevs);
        }
开发者ID:orlovk,项目名称:PtProject,代码行数:37,代码来源:GaussianTransform.cs


示例2: PerformCrossValidation

 /// <summary>
 /// Performs cross validation.
 /// </summary>
 /// <param name="problem">The training data</param>
 /// <param name="parameters">The parameters to test</param>
 /// <param name="nrfold">The number of cross validations to use</param>
 /// <returns>The cross validation score</returns>
 public static double PerformCrossValidation(Problem problem, Parameter parameters, int nrfold)
 {
     string error = Procedures.svm_check_parameter(problem, parameters);
     if (error == null)
         return doCrossValidation(problem, parameters, nrfold);
     else throw new Exception(error);
 }
开发者ID:hksonngan,项目名称:mytesgnikrow,代码行数:14,代码来源:Training.cs


示例3: Scale

 /// <summary>
 /// Scales a problem using the provided range.  This will not affect the parameter.
 /// </summary>
 /// <param name="prob">The problem to scale</param>
 /// <param name="range">The Range transform to use in scaling</param>
 /// <returns>The Scaled problem</returns>
 public static Problem Scale(this IRangeTransform range, Problem prob)
 {
     Problem scaledProblem = new Problem(prob.Count, new double[prob.Count], new Node[prob.Count][], prob.MaxIndex);
     for (int i = 0; i < scaledProblem.Count; i++)
     {
         scaledProblem.X[i] = new Node[prob.X[i].Length];
         for (int j = 0; j < scaledProblem.X[i].Length; j++)
             scaledProblem.X[i][j] = new Node(prob.X[i][j].Index, range.Transform(prob.X[i][j].Value, prob.X[i][j].Index));
         scaledProblem.Y[i] = prob.Y[i];
     }
     return scaledProblem;
 }
开发者ID:hksonngan,项目名称:mytesgnikrow,代码行数:18,代码来源:Scaling.cs


示例4: train

        public Model train(Problem issue)
        {
            var span = Overseer.observe("Training.Parameter-Choosing");
            Parameter parameters = new Parameter();
            parameters.KernelType = KernelType.RBF;
            double C;
            double Gamma;

            ParameterSelection.Grid(issue, parameters, null, out C, out Gamma);
            parameters.C = C;
            parameters.Gamma = Gamma;
            span.die();
            span = Overseer.observe("Training.Training");
            var result = Training.Train(issue, parameters);
            span.die();
            return result;
        }
开发者ID:Termina1,项目名称:diploma-svm-face-project,代码行数:17,代码来源:Trainer.cs


示例5: svm_train_one

        static decision_function svm_train_one(Problem prob, Parameter param, double Cp, double Cn)
        {
            double[] alpha = new double[prob.Count];
            Solver.SolutionInfo si = new Solver.SolutionInfo();
            switch (param.SvmType)
            {
                case SvmType.C_SVC:
                    solve_c_svc(prob, param, alpha, si, Cp, Cn);
                    break;
                case SvmType.NU_SVC:
                    solve_nu_svc(prob, param, alpha, si);
                    break;
                case SvmType.ONE_CLASS:
                    solve_one_class(prob, param, alpha, si);
                    break;
                case SvmType.EPSILON_SVR:
                    solve_epsilon_svr(prob, param, alpha, si);
                    break;
                case SvmType.NU_SVR:
                    solve_nu_svr(prob, param, alpha, si);
                    break;
            }

            Procedures.info("obj = " + si.obj + ", rho = " + si.rho + "\n");

            // output SVs

            int nSV = 0;
            int nBSV = 0;
            for (int i = 0; i < prob.Count; i++)
            {
                if (Math.Abs(alpha[i]) > 0)
                {
                    ++nSV;
                    if (prob.Y[i] > 0)
                    {
                        if (Math.Abs(alpha[i]) >= si.upper_bound_p)
                            ++nBSV;
                    }
                    else
                    {
                        if (Math.Abs(alpha[i]) >= si.upper_bound_n)
                            ++nBSV;
                    }
                }
            }

            Procedures.info("nSV = " + nSV + ", nBSV = " + nBSV + "\n");

            decision_function f = new decision_function();
            f.alpha = alpha;
            f.rho = si.rho;
            return f;
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:54,代码来源:Solver.cs


示例6: svm_group_classes

        // label: label name, start: begin of each class, count: #data of classes, perm: indices to the original data
        // perm, length l, must be allocated before calling this subroutine
        private static void svm_group_classes(Problem prob, int[] nr_class_ret, int[][] label_ret, int[][] start_ret, int[][] count_ret, int[] perm)
        {
            int l = prob.Count;
            int Max_nr_class = 16;
            int nr_class = 0;
            int[] label = new int[Max_nr_class];
            int[] count = new int[Max_nr_class];
            int[] data_label = new int[l];
            int i;

            for (i = 0; i < l; i++)
            {
                int this_label = (int)(prob.Y[i]);
                int j;
                for (j = 0; j < nr_class; j++)
                {
                    if (this_label == label[j])
                    {
                        ++count[j];
                        break;
                    }
                }
                data_label[i] = j;
                if (j == nr_class)
                {
                    if (nr_class == Max_nr_class)
                    {
                        Max_nr_class *= 2;
                        int[] new_data = new int[Max_nr_class];
                        Array.Copy(label, 0, new_data, 0, label.Length);
                        label = new_data;
                        new_data = new int[Max_nr_class];
                        Array.Copy(count, 0, new_data, 0, count.Length);
                        count = new_data;
                    }
                    label[nr_class] = this_label;
                    count[nr_class] = 1;
                    ++nr_class;
                }
            }

            int[] start = new int[nr_class];
            start[0] = 0;
            for (i = 1; i < nr_class; i++)
                start[i] = start[i - 1] + count[i - 1];
            for (i = 0; i < l; i++)
            {
                perm[start[data_label[i]]] = i;
                ++start[data_label[i]];
            }
            start[0] = 0;
            for (i = 1; i < nr_class; i++)
                start[i] = start[i - 1] + count[i - 1];

            nr_class_ret[0] = nr_class;
            label_ret[0] = label;
            start_ret[0] = start;
            count_ret[0] = count;
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:61,代码来源:Solver.cs


示例7: svm_svr_probability

        // Return parameter of a Laplace distribution
        private static double svm_svr_probability(Problem prob, Parameter param)
        {
            int i;
            int nr_fold = 5;
            double[] ymv = new double[prob.Count];
            double mae = 0;

            Parameter newparam = (Parameter)param.Clone();
            newparam.Probability = false;
            svm_cross_validation(prob, newparam, nr_fold, ymv);
            for (i = 0; i < prob.Count; i++)
            {
                ymv[i] = prob.Y[i] - ymv[i];
                mae += Math.Abs(ymv[i]);
            }
            mae /= prob.Count;
            double std = Math.Sqrt(2 * mae * mae);
            int count = 0;
            mae = 0;
            for (i = 0; i < prob.Count; i++)
                if (Math.Abs(ymv[i]) > 5 * std)
                    count = count + 1;
                else
                    mae += Math.Abs(ymv[i]);
            mae /= (prob.Count - count);
            Procedures.info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + mae + "\n");
            return mae;
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:29,代码来源:Solver.cs


示例8: Grid

 /// <summary>
 /// Performs a Grid parameter selection, trying all possible combinations of the two lists and returning the
 /// combination which performed best.  Use this method if there is no validation data available, and it will
 /// divide it 5 times to allow 5-fold validation (training on 4/5 and validating on 1/5, 5 times).
 /// </summary>
 /// <param name="problem">The training data</param>
 /// <param name="parameters">The parameters to use when optimizing</param>
 /// <param name="CValues">The set of C values to use</param>
 /// <param name="GammaValues">The set of Gamma values to use</param>
 /// <param name="outputFile">Output file for the parameter results.</param>
 /// <param name="C">The optimal C value will be put into this variable</param>
 /// <param name="Gamma">The optimal Gamma value will be put into this variable</param>
 public static void Grid(
     Problem problem,
     Parameter parameters,
     List<double> CValues,
     List<double> GammaValues,
     string outputFile,
     out double C,
     out double Gamma)
 {
     Grid(problem, parameters, CValues, GammaValues, outputFile, NFOLD, out C, out Gamma);
 }
开发者ID:Termina1,项目名称:libsvm-csharp,代码行数:23,代码来源:ParameterSelection.cs


示例9: svm_binary_svc_probability

        // Cross-validation decision values for probability estimates
        private static void svm_binary_svc_probability(Problem prob, Parameter param, double Cp, double Cn, double[] probAB)
        {
            int i;
            int nr_fold = 5;
            int[] perm = new int[prob.Count];
            double[] dec_values = new double[prob.Count];

            // random shuffle
            Random rand = new Random();
            for (i = 0; i < prob.Count; i++) perm[i] = i;
            for (i = 0; i < prob.Count; i++)
            {
                int j = i + (int)(rand.NextDouble() * (prob.Count - i));
                do { int _ = perm[i]; perm[i] = perm[j]; perm[j] = _; } while (false);
            }
            for (i = 0; i < nr_fold; i++)
            {
                int begin = i * prob.Count / nr_fold;
                int end = (i + 1) * prob.Count / nr_fold;
                int j, k;
                Problem subprob = new Problem();

                subprob.Count = prob.Count - (end - begin);
                subprob.X = new Node[subprob.Count][];
                subprob.Y = new double[subprob.Count];

                k = 0;
                for (j = 0; j < begin; j++)
                {
                    subprob.X[k] = prob.X[perm[j]];
                    subprob.Y[k] = prob.Y[perm[j]];
                    ++k;
                }
                for (j = end; j < prob.Count; j++)
                {
                    subprob.X[k] = prob.X[perm[j]];
                    subprob.Y[k] = prob.Y[perm[j]];
                    ++k;
                }
                int p_count = 0, n_count = 0;
                for (j = 0; j < k; j++)
                    if (subprob.Y[j] > 0)
                        p_count++;
                    else
                        n_count++;

                if (p_count == 0 && n_count == 0)
                    for (j = begin; j < end; j++)
                        dec_values[perm[j]] = 0;
                else if (p_count > 0 && n_count == 0)
                    for (j = begin; j < end; j++)
                        dec_values[perm[j]] = 1;
                else if (p_count == 0 && n_count > 0)
                    for (j = begin; j < end; j++)
                        dec_values[perm[j]] = -1;
                else
                {
                    Parameter subparam = (Parameter)param.Clone();
                    subparam.Probability = false;
                    subparam.C = 1.0;
                    subparam.Weights[1] = Cp;
                    subparam.Weights[-1] = Cn;
                    Model submodel = svm_train(subprob, subparam);
                    for (j = begin; j < end; j++)
                    {
                        double[] dec_value = new double[1];
                        svm_predict_values(submodel, prob.X[perm[j]], dec_value);
                        dec_values[perm[j]] = dec_value[0];
                        // ensure +1 -1 order; reason not using CV subroutine
                        dec_values[perm[j]] *= submodel.ClassLabels[0];
                    }
                }
            }
            sigmoid_train(prob.Count, dec_values, prob.Y, probAB);
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:76,代码来源:Solver.cs


示例10: SVC_Q

 public SVC_Q(Problem prob, Parameter param, sbyte[] y_)
     : base(prob.Count, prob.X, param)
 {
     y = (sbyte[])y_.Clone();
     cache = new Cache(prob.Count, (long)(param.CacheSize * (1 << 20)));
     QD = new float[prob.Count];
     for (int i = 0; i < prob.Count; i++)
         QD[i] = (float)KernelFunction(i, i);
 }
开发者ID:wendelad,项目名称:RecSys,代码行数:9,代码来源:Solver.cs


示例11: svm_train

        //
        // Interface functions
        //
        public static Model svm_train(Problem prob, Parameter param)
        {
            Model model = new Model();
            model.Parameter = param;

            if (param.SvmType == SvmType.ONE_CLASS ||
               param.SvmType == SvmType.EPSILON_SVR ||
               param.SvmType == SvmType.NU_SVR)
            {
                // regression or one-class-svm
                model.NumberOfClasses = 2;
                model.ClassLabels = null;
                model.NumberOfSVPerClass = null;
                model.PairwiseProbabilityA = null; model.PairwiseProbabilityB = null;
                model.SupportVectorCoefficients = new double[1][];

                if (param.Probability &&
                   (param.SvmType == SvmType.EPSILON_SVR ||
                    param.SvmType == SvmType.NU_SVR))
                {
                    model.PairwiseProbabilityA = new double[1];
                    model.PairwiseProbabilityA[0] = svm_svr_probability(prob, param);
                }

                decision_function f = svm_train_one(prob, param, 0, 0);
                model.Rho = new double[1];
                model.Rho[0] = f.rho;

                int nSV = 0;
                int i;
                for (i = 0; i < prob.Count; i++)
                    if (Math.Abs(f.alpha[i]) > 0) ++nSV;
                model.SupportVectorCount = nSV;
                model.SupportVectors = new Node[nSV][];
                model.SupportVectorCoefficients[0] = new double[nSV];
                int j = 0;
                for (i = 0; i < prob.Count; i++)
                    if (Math.Abs(f.alpha[i]) > 0)
                    {
                        model.SupportVectors[j] = prob.X[i];
                        model.SupportVectorCoefficients[0][j] = f.alpha[i];
                        ++j;
                    }
            }
            else
            {
                // classification
                int l = prob.Count;
                int[] tmp_nr_class = new int[1];
                int[][] tmp_label = new int[1][];
                int[][] tmp_start = new int[1][];
                int[][] tmp_count = new int[1][];
                int[] perm = new int[l];

                // group training data of the same class
                svm_group_classes(prob, tmp_nr_class, tmp_label, tmp_start, tmp_count, perm);
                int nr_class = tmp_nr_class[0];
                int[] label = tmp_label[0];
                int[] start = tmp_start[0];
                int[] count = tmp_count[0];
                Node[][] x = new Node[l][];
                int i;
                for (i = 0; i < l; i++)
                    x[i] = prob.X[perm[i]];

                // calculate weighted C

                double[] weighted_C = new double[nr_class];
                for (i = 0; i < nr_class; i++)
                    weighted_C[i] = param.C;
                foreach (int weightedLabel in param.Weights.Keys)
                {
                    int index = Array.IndexOf<int>(label, weightedLabel);
                    if (index < 0)
                        Console.Error.WriteLine("warning: class label " + weightedLabel + " specified in weight is not found");
                    else weighted_C[index] *= param.Weights[weightedLabel];
                }

                // train k*(k-1)/2 models

                bool[] nonzero = new bool[l];
                for (i = 0; i < l; i++)
                    nonzero[i] = false;
                decision_function[] f = new decision_function[nr_class * (nr_class - 1) / 2];

                double[] probA = null, probB = null;
                if (param.Probability)
                {
                    probA = new double[nr_class * (nr_class - 1) / 2];
                    probB = new double[nr_class * (nr_class - 1) / 2];
                }

                int p = 0;
                for (i = 0; i < nr_class; i++)
                    for (int j = i + 1; j < nr_class; j++)
                    {
                        Problem sub_prob = new Problem();
//.........这里部分代码省略.........
开发者ID:wendelad,项目名称:RecSys,代码行数:101,代码来源:Solver.cs


示例12: LearnAttributeToFactorMapping

        ///
        public override void LearnAttributeToFactorMapping()
        {
            var svm_features = new List<Node[]>();
            var relevant_items  = new List<int>();
            for (int i = 0; i < MaxItemID + 1; i++)
            {
                // ignore items w/o collaborative data
                if (Feedback.ItemMatrix[i].Count == 0)
                    continue;
                // ignore items w/o attribute data
                if (item_attributes[i].Count == 0)
                    continue;

                svm_features.Add( CreateNodes(i) );
                relevant_items.Add(i);
            }

            // TODO proper random seed initialization

            Node[][] svm_features_array = svm_features.ToArray();
            var svm_parameters = new Parameter();
            svm_parameters.SvmType = SvmType.EPSILON_SVR;
            //svm_parameters.SvmType = SvmType.NU_SVR;
            svm_parameters.C     = this.c;
            svm_parameters.Gamma = this.gamma;

            models = new Model[num_factors];
            for (int f = 0; f < num_factors; f++)
            {
                double[] targets = new double[svm_features.Count];
                for (int i = 0; i < svm_features.Count; i++)
                {
                    int item_id = relevant_items[i];
                    targets[i] = item_factors[item_id, f];
                }

                Problem svm_problem = new Problem(svm_features.Count, targets, svm_features_array, NumItemAttributes - 1);
                models[f] = SVM.Training.Train(svm_problem, svm_parameters);
            }

            _MapToLatentFactorSpace = Utils.Memoize<int, float[]>(__MapToLatentFactorSpace);
        }
开发者ID:kinyue,项目名称:MyMediaLite,代码行数:43,代码来源:BPRMF_ItemMappingSVR.cs


示例13: startSurfTrain

        public void startSurfTrain()
        {
            List<FileInfo> trainingFiles = new List<FileInfo>(1000);
            DirectoryInfo di = new DirectoryInfo(Constants.base_folder + "train_" + Constants.CIRCLE_TRIANGLE);
            DirectoryInfo[] dirs = di.GetDirectories("*");
            foreach (DirectoryInfo dir in dirs)
            {
                int i = 0;
                FileInfo[] files = dir.GetFiles("*.bmp");
                foreach (FileInfo fi in files)
                {
                    trainingFiles.Add(fi);
                    if (i++ > Constants.MAX_TRAIN_SAMPLE)
                        break;
                }
            }

            double[] class_labels = new double[trainingFiles.Count];
            Node[][] nodes = new Node[trainingFiles.Count][];

            for (int i = 0; i < trainingFiles.Count; i++)
            {
                Bitmap bmp = (Bitmap)Bitmap.FromFile(trainingFiles[i].FullName, false);

                int com_x_sum = 0, com_y_sum = 0, com_x_y_point_count = 0;
                System.Drawing.Imaging.BitmapData image_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
                int bpp = 3;
                int nOffset = image_data.Stride - bmp.Width * bpp;
                System.IntPtr Scan0 = image_data.Scan0;
                unsafe
                {
                    byte* p = (byte*)Scan0;
                    for (int y = 0; y < Constants.SIGN_HEIGHT; y++)
                    {
                        for (int x = 0; x < Constants.SIGN_WIDTH; x++, p += bpp)
                        {
                            if (p[2] == 0)
                            {
                                com_x_sum += x;
                                com_y_sum += y;
                                com_x_y_point_count++;
                            }
                        }
                        p += nOffset;
                    }
                }
                bmp.UnlockBits(image_data);
                int com_x = com_x_sum / com_x_y_point_count;
                int com_y = com_y_sum / com_x_y_point_count;

                Node[] nds = new Node[NNTrain.numOfinputs];
                nodes[i] = nds;

                bmp.Tag = trainingFiles[i].Name;
                fillFeatures_SURF(bmp, com_x, com_y, nds);
                class_labels[i] = Double.Parse(trainingFiles[i].Directory.Name);
            }
            Problem problem = new Problem(nodes.Length, class_labels, nodes, NNTrain.numOfinputs + 1);
            // RangeTransform range = Scaling.DetermineRange(problem);
            // problem = Scaling.Scale(problem, range);

            Parameter param = new Parameter();
            param.KernelType = KernelType.POLY;
            // param.KernelType = KernelType.LINEAR;
            // param.KernelType = KernelType.RBF;
            param.SvmType = SvmType.NU_SVC;

            param.C = 2;
            param.Gamma = .5;
            //param.KernelType = KernelType.POLY;

            /* double C, Gamma;
            ParameterSelection.Grid(problem, param, Constants.base_folder + "params_" + type + ".txt", out C, out Gamma);
            param.C = C;
            param.Gamma = Gamma;
            //param.Probability = true;
            */
            Model model = Training.Train(problem, param);

            Stream stream = new FileStream(Constants.base_folder + Constants.NN_SVM_SURF + "_" + Constants.CIRCLE_TRIANGLE + ".dat", FileMode.Create, FileAccess.Write, FileShare.None);
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(stream, model);
            stream.Close();
        }
开发者ID:adesproject,项目名称:ADES,代码行数:84,代码来源:SVMTrain.cs


示例14: backgroundWorker_DoWork

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Problem problem = new Problem(_X.Count, _Y.ToArray(), _X.ToArray(), 2);
            RangeTransform range = RangeTransform.Compute(problem);
            problem = range.Scale(problem);

            Parameter param = new Parameter();
            param.C = 2;
            param.Gamma = .5;
            Model model = Training.Train(problem, param);

            Model.Write("model.txt", model);

            int rows = ClientSize.Height;
            int columns = ClientSize.Width;
            Bitmap image = new Bitmap(columns, rows);
            int centerR = rows / 2;
            int centerC = columns / 2;
            BitmapData buf = image.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
            unsafe
            {
                byte* ptr = (byte*)buf.Scan0;
                int stride = buf.Stride;

                for (int r = 0; r < rows; r++)
                {
                    byte* scan = ptr;
                    for (int c = 0; c < columns; c++)
                    {
                        int x = c - centerC;
                        int y = r - centerR;
                        Node[] test = new Node[] { new Node(1, x), new Node(2, y) };
                        test = range.Transform(test);
                        int assignment = (int)Prediction.Predict(model, test);
                        //int assignment = (int)Prediction.Predict(problem, "predict.txt", model, test);

                        *scan++ = CLASS_FILL[assignment].B;
                        *scan++ = CLASS_FILL[assignment].G;
                        *scan++ = CLASS_FILL[assignment].R;
                    }
                    ptr += stride;
                }
            }
            image.UnlockBits(buf);
            lock (this)
            {
                _canvas = new Bitmap(image);
            }
        }
开发者ID:hksonngan,项目名称:mytesgnikrow,代码行数:49,代码来源:SVMCanvas.cs


示例15: Train

        ///
        public override void Train()
        {
            int num_users = Feedback.UserMatrix.NumberOfRows;   // DH: should be based on MaxUserID for cold case? TODO: investigate.
            int num_items = Feedback.ItemMatrix.NumberOfRows;

            var svm_features = new List<Node[]>();

            Node[][] svm_features_array = svm_features.ToArray();
            var svm_parameters = new Parameter();
            svm_parameters.SvmType = SvmType.EPSILON_SVR;
            //svm_parameters.SvmType = SvmType.NU_SVR;
            svm_parameters.C     = this.c;
            svm_parameters.Gamma = this.gamma;

            // user-wise training
            this.models = new Model[num_users];
            for (int u = 0; u < num_users; u++)
            {
                var targets = new double[num_items];
                for (int i = 0; i < num_items; i++)
                    targets[i] = Feedback.UserMatrix[u, i] ? 1 : 0;

                Problem svm_problem = new Problem(svm_features.Count, targets, svm_features_array, NumItemAttributes - 1); // TODO check
                models[u] = SVM.Training.Train(svm_problem, svm_parameters);
            }
        }
开发者ID:dylanhogg,项目名称:MyMediaLite,代码行数:27,代码来源:ItemAttributeSVM.cs


示例16: svm_cross_validation

        // Stratified cross validation
        public static void svm_cross_validation(Problem prob, Parameter param, int nr_fold, double[] target)
        {
            Random rand = new Random();
            int i;
            int[] fold_start = new int[nr_fold + 1];
            int l = prob.Count;
            int[] perm = new int[l];

            // stratified cv may not give leave-one-out rate
            // Each class to l folds -> some folds may have zero elements
            if ((param.SvmType == SvmType.C_SVC ||
                param.SvmType == SvmType.NU_SVC) && nr_fold < l)
            {
                int[] tmp_nr_class = new int[1];
                int[][] tmp_label = new int[1][];
                int[][] tmp_start = new int[1][];
                int[][] tmp_count = new int[1][];

                svm_group_classes(prob, tmp_nr_class, tmp_label, tmp_start, tmp_count, perm);

                int nr_class = tmp_nr_class[0];
                //int[] label = tmp_label[0];
                int[] start = tmp_start[0];
                int[] count = tmp_count[0];

                // random shuffle and then data grouped by fold using the array perm
                int[] fold_count = new int[nr_fold];
                int c;
                int[] index = new int[l];
                for (i = 0; i < l; i++)
                    index[i] = perm[i];
                for (c = 0; c < nr_class; c++)
                    for (i = 0; i < count[c]; i++)
                    {
                        int j = i + (int)(rand.NextDouble() * (count[c] - i));
                        do { int _ = index[start[c] + j]; index[start[c] + j] = index[start[c] + i]; index[start[c] + i] = _; } while (false);
                    }
                for (i = 0; i < nr_fold; i++)
                {
                    fold_count[i] = 0;
                    for (c = 0; c < nr_class; c++)
                        fold_count[i] += (i + 1) * count[c] / nr_fold - i * count[c] / nr_fold;
                }
                fold_start[0] = 0;
                for (i = 1; i <= nr_fold; i++)
                    fold_start[i] = fold_start[i - 1] + fold_count[i - 1];
                for (c = 0; c < nr_class; c++)
                    for (i = 0; i < nr_fold; i++)
                    {
                        int begin = start[c] + i * count[c] / nr_fold;
                        int end = start[c] + (i + 1) * count[c] / nr_fold;
                        for (int j = begin; j < end; j++)
                        {
                            perm[fold_start[i]] = index[j];
                            fold_start[i]++;
                        }
                    }
                fold_start[0] = 0;
                for (i = 1; i <= nr_fold; i++)
                    fold_start[i] = fold_start[i - 1] + fold_count[i - 1];
            }
            else
            {
                for (i = 0; i < l; i++) perm[i] = i;
                for (i = 0; i < l; i++)
                {
                    int j = i + (int)(rand.NextDouble() * (l - i));
                    do { int _ = perm[i]; perm[i] = perm[j]; perm[j] = _; } while (false);
                }
                for (i = 0; i <= nr_fold; i++)
                    fold_start[i] = i * l / nr_fold;
            }

            for (i = 0; i < nr_fold; i++)
            {
                int begin = fold_start[i];
                int end = fold_start[i + 1];
                int j, k;
                Problem subprob = new Problem();

                subprob.Count = l - (end - begin);
                subprob.X = new Node[subprob.Count][];
                subprob.Y = new double[subprob.Count];

                k = 0;
                for (j = 0; j < begin; j++)
                {
                    subprob.X[k] = prob.X[perm[j]];
                    subprob.Y[k] = prob.Y[perm[j]];
                    ++k;
                }
                for (j = end; j < l; j++)
                {
                    subprob.X[k] = prob.X[perm[j]];
                    subprob.Y[k] = prob.Y[perm[j]];
                    ++k;
                }
                Model submodel = svm_train(subprob, param);
                if (param.Probability &&
//.........这里部分代码省略.........
开发者ID:wendelad,项目名称:RecSys,代码行数:101,代码来源:Solver.cs


示例17: solve_c_svc

        private static void solve_c_svc(Problem prob, Parameter param,
                        double[] alpha, Solver.SolutionInfo si,
                        double Cp, double Cn)
        {
            int l = prob.Count;
            double[] Minus_ones = new double[l];
            sbyte[] y = new sbyte[l];

            int i;

            for (i = 0; i < l; i++)
            {
                alpha[i] = 0;
                Minus_ones[i] = -1;
                if (prob.Y[i] > 0) y[i] = +1; else y[i] = -1;
            }

            Solver s = new Solver();
            s.Solve(l, new SVC_Q(prob, param, y), Minus_ones, y,
                alpha, Cp, Cn, param.EPS, si, param.Shrinking);

            double sum_alpha = 0;
            for (i = 0; i < l; i++)
                sum_alpha += alpha[i];

            if (Cp == Cn)
                Procedures.info("nu = " + sum_alpha / (Cp * prob.Count) + "\n");

            for (i = 0; i < l; i++)
                alpha[i] *= y[i];
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:31,代码来源:Solver.cs


示例18: ONE_CLASS_Q

 public ONE_CLASS_Q(Problem prob, Parameter param)
     : base(prob.Count, prob.X, param)
 {
     cache = new Cache(prob.Count, (long)(param.CacheSize * (1 << 20)));
     QD = new float[prob.Count];
     for (int i = 0; i < prob.Count; i++)
         QD[i] = (float)KernelFunction(i, i);
 }
开发者ID:wendelad,项目名称:RecSys,代码行数:8,代码来源:Solver.cs


示例19: solve_nu_svc

        private static void solve_nu_svc(Problem prob, Parameter param,
                        double[] alpha, Solver.SolutionInfo si)
        {
            int i;
            int l = prob.Count;
            double nu = param.Nu;

            sbyte[] y = new sbyte[l];

            for (i = 0; i < l; i++)
                if (prob.Y[i] > 0)
                    y[i] = +1;
                else
                    y[i] = -1;

            double sum_pos = nu * l / 2;
            double sum_neg = nu * l / 2;

            for (i = 0; i < l; i++)
                if (y[i] == +1)
                {
                    alpha[i] = Math.Min(1.0, sum_pos);
                    sum_pos -= alpha[i];
                }
                else
                {
                    alpha[i] = Math.Min(1.0, sum_neg);
                    sum_neg -= alpha[i];
                }

            double[] zeros = new double[l];

            for (i = 0; i < l; i++)
                zeros[i] = 0;

            Solver_NU s = new Solver_NU();
            s.Solve(l, new SVC_Q(prob, param, y), zeros, y, alpha, 1.0, 1.0, param.EPS, si, param.Shrinking);
            double r = si.r;

            Procedures.info("C = " + 1 / r + "\n");

            for (i = 0; i < l; i++)
                alpha[i] *= y[i] / r;

            si.rho /= r;
            si.obj /= (r * r);
            si.upper_bound_p = 1 / r;
            si.upper_bound_n = 1 / r;
        }
开发者ID:wendelad,项目名称:RecSys,代码行数:49,代码来源:Solver.cs


示例20: SVR_Q

 public SVR_Q(Problem prob, Parameter param)
     : base(prob.Count, prob.X, param)
 {
     l = prob.Count;
     cache = new Cache(l, (long)(param.CacheSize * (1 << 20)));
     QD = new float[2 * l];
     sign = new sbyte[2 * l];
     index = new int[2 * l];
     for (int k = 0; k < l; k++)
     {
         sign[k] = 1;
         sign[k + l] = -1;
         index[k] = k;
         index[k + l] = k;
         QD[k] = (float)KernelFunction(k, k);
         QD[k + l] = QD[k];
     }
     buffer = new float[2][];
     buffer[0] = new float[2 * l];
     buffer[1] = new float[2 * l];
     next_buffer = 0;
 }
开发者ID:wendelad,项目名称:RecSys,代码行数:22,代码来源:Solver.cs



注:本文中的SVM.Problem类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SYSModel.DataSources类代码示例发布时间:2022-05-26
下一篇:
C# SVM.Parameter类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap