C# 无法使SVM像我预期的那样工作

C# 无法使SVM像我预期的那样工作,c#,opencv,svm,emgucv,C#,Opencv,Svm,Emgucv,这方面我是新手。我尝试做的是为同一个数据集训练多个支持向量机,使用不同的参数(我希望将来会有不同类型的图像签名),然后预测每个支持向量机并接受最常见的类 我试着阅读很多人关于SVM图像训练的代码,但不知道我在我的代码中做错了什么。无论我尝试什么,svm.Predict总是返回0 非常感谢任何帮助或暗示 internal class SVMClassifier { Dictionary<int, string> classIndex_name;

这方面我是新手。我尝试做的是为同一个数据集训练多个支持向量机,使用不同的参数(我希望将来会有不同类型的图像签名),然后预测每个支持向量机并接受最常见的类

我试着阅读很多人关于SVM图像训练的代码,但不知道我在我的代码中做错了什么。无论我尝试什么,svm.Predict总是返回0

非常感谢任何帮助或暗示

    internal class SVMClassifier
    {
        Dictionary<int, string> classIndex_name;
        List<SVM> svms;

        internal void Train(string trainFolder)
        {
            this.classIndex_name = new Dictionary<int, string>();
            Dictionary<int, List<Mat>> class_mats = getMats(trainFolder, this.classIndex_name);
            this.svms = new List<SVM>();


            Mat samples; Mat responses;
            getTrainingData(class_mats, out samples, out responses);
            svms.Add(trainSVM(samples, responses));
            svms.Add(trainSVM(samples, responses, SVM.SvmType.CSvc, SVM.SvmKernelType.Linear, 0d, 0d, 10d, TermCritType.Iter | TermCritType.Eps, 1000, 0.000001d, 0d, 0d));
            svms.Add(trainSVM(samples, responses, SVM.SvmType.CSvc, SVM.SvmKernelType.Rbf, 100d, 100d, 1d, TermCritType.Iter | TermCritType.Eps, 1000, 0.000001d, 0.1d, 0.5d));

            samples.Dispose(); responses.Dispose();

            foreach (Mat mat in class_mats.Values.SelectMany((a) => a))
                mat.Dispose();
        }
        private static Dictionary<int, List<Mat>> getMats(string trainFolder, Dictionary<int, string> classIndex_name)
        {
            Dictionary<int, List<Mat>> class_mats = new Dictionary<int, List<Mat>>();
            DirectoryInfo diTrain = new DirectoryInfo(trainFolder);
            int i = 0;
            foreach (var di in diTrain.GetDirectories())//classes are according to the directories
            {
                var dirName = di.Name;
                classIndex_name[i] = dirName;
                var fileNames = di.GetFiles().Select((a) => a.FullName).ToList();
                fileNames.Sort(new Dece.Misc.NumericSuffixFileFullNameComparer());
                class_mats[i] = fileNames.Select((a) => getMat(a, true)).ToList();
                i++;
            }
            return class_mats;
        }

        private static SVM trainSVM(Mat samples, Mat responses,
            SVM.SvmType? svm_Type = null, SVM.SvmKernelType? svm_KernelType = null, double? gamma = null, double? degree = null, double? c = null,
            TermCritType? criteriaType = null, int? criteriaMaxCount = null, double? criteriaEps = null, double? p = null, double? nu=null)
        {
            SVM svm = new SVM();
            if (svm_Type != null) svm.Type = (SVM.SvmType)svm_Type;
            if (svm_KernelType != null) svm.SetKernel((SVM.SvmKernelType)svm_KernelType);
            if (gamma != null) svm.Gamma = (double)gamma;
            if (degree != null) svm.Degree = (double)degree;
            if (c != null) svm.C = (double)c;

            if ((criteriaType != null) || (criteriaMaxCount != null) || (criteriaEps != null))
            {
                var t = new MCvTermCriteria((int)criteriaMaxCount, (double)criteriaEps);
                if (criteriaType != null) t.Type = (TermCritType)criteriaType;
                svm.TermCriteria = t;
            }


            if (p != null) svm.P = (double)p;
            if (nu != null) svm.Nu = (double)nu;

            if (!svm.Train(samples, DataLayoutType.RowSample, responses))
                throw new Exception();
            return svm;
        }

        private static void getTrainingData(Dictionary<int, List<Mat>> class_mats, out Mat samples, out Mat responses)
        {
            samples = null;
            List<int> lstResp = new List<int>();
            foreach (int cls in class_mats.Keys)
            {
                int count = 0;
                foreach (Mat mat in class_mats[cls])
                    using (var desc = mat.Reshape(0, 1))
                    {
                        if (samples == null)
                            samples = new Mat(desc.Cols, 0, desc.Depth, 1);
                        samples.PushBack(desc);
                        count += desc.Rows;
                    }
                for (int i = 0; i < count; i++)
                    lstResp.Add(cls);
            }

            //responses = new Mat(new Size(lstResp.Count, 1), DepthType.Cv32S, 1);
            //for (int i = 0; i < lstResp.Count; i++)
            //    responses.SetValue(0, i, lstResp[i]);

            responses = new Mat(new Size(1, lstResp.Count), DepthType.Cv32S, 1);
            for (int i = 0; i < lstResp.Count; i++)
                responses.SetValue(i, 0, lstResp[i]);

            if (samples.Depth != DepthType.Cv32F)
                samples.ConvertTo(samples, DepthType.Cv32F);

            CvInvoke.Normalize(samples, samples, -1, 1, NormType.MinMax);
        }

        internal void Detect(IEnumerable<string> fileNames, Action<ShapeInfo> detected)
        {
            foreach (var fn in fileNames)
                using (Mat mat = getMat(fn, false))
                {
                    {
                        using (var samples = mat.Reshape(0, 1))
                        {
                            if (samples.Depth != DepthType.Cv32F)
                                samples.ConvertTo(samples, DepthType.Cv32F);
                            CvInvoke.Normalize(samples, samples, -1, 1, NormType.MinMax);
                            foreach (var svm in this.svms)
                            {
                                Mat res = new Mat();
                                float p0 = svm.Predict(samples, res, 0);
                                float p1 = svm.Predict(samples, res, 1);
                                float p2 = svm.Predict(samples, res, 2);
                                float p3 = svm.Predict(samples, res, 3);
                                float p4 = svm.Predict(samples, res, 4);
                                float p = svm.Predict(samples, res);

                                foreach (var val in toIEnumerable(p0, p1, p2, p3, p4, p))
                                    if (val != 0f)
                                    {
                                        System.Windows.Forms.MessageBox.Show("never enters here :(");
                                    }
                            }
                        }
                    }
                }
        }

        private static Mat getMat(string fn, bool train)
        {
            var mat = new Mat(fn, ImreadModes.Grayscale);
            mat.Resize(new Size(128, 128));
            return mat;
        }
        private static IEnumerable<T> toIEnumerable<T>(params T[] items)
        {
            if (items != null)
                foreach (var item in items)
                    yield return item;
        }

    }
内部类SVMC分类器
{
字典分类索引名称;
列出支持向量机;
内部无效序列(字符串序列文件夹)
{
this.classIndex_name=新字典();
Dictionary class_mats=getMats(trainFolder,this.classIndex_名称);
this.svms=新列表();
Mat样品;Mat响应;
获取培训数据(类别、样本、响应);
添加(训练SVM(样本、响应));
svms.Add(训练SVM(样本、响应、SVM.SvmType.CSvc、SVM.SvmKernelType.Linear、0d、0d、10d、TermCritType.Iter | TermCritType.Eps、1000、0.000001d、0d、0d));
svms.Add(训练SVM(样本、响应、SVM.SvmType.CSvc、SVM.SvmKernelType.Rbf、100d、100d、1d、TermCritType.Iter | TermCritType.Eps、1000、0.000001d、0.1d、0.5d));
samples.Dispose();responses.Dispose();
foreach(类中的Mat_mats.Values.SelectMany((a)=>a))
mat.Dispose();
}
私有静态字典getMats(字符串trainFolder,字典classIndex_name)
{
字典类_mats=新字典();
DirectoryInfo diTrain=新的DirectoryInfo(trainFolder);
int i=0;
foreach(diTrain.GetDirectories()中的var di)//类根据目录
{
var dirName=di.Name;
classIndex_name[i]=目录名;
var fileNames=di.GetFiles().Select((a)=>a.FullName.ToList();
排序(新的Dece.Misc.NumericSuffixFileFullNameComparer());
class_mats[i]=文件名。选择((a)=>getMat(a,true)).ToList();
i++;
}
返回舱垫;
}
专用静态SVM训练SVM(Mat样本、Mat响应、,
SVM.SvmType?SVM_Type=null,SVM.SvmKernelType?SVM_KernelType=null,double?gamma=null,double?degree=null,double?c=null,
TERMCRITYPE?criteriaType=null,int?criteriaMaxCount=null,double?criteriaEps=null,double?p=null,double?nu=null)
{
SVM=新的SVM();
如果(svm_Type!=null)svm.Type=(svm.SvmType)svm_Type;
if(svm_KernelType!=null)svm.SetKernel((svm.SvmKernelType)svm_KernelType);
如果(gamma!=null)svm.gamma=(double)gamma;
如果(度!=null)svm.degree=(双)度;
如果(c!=null)svm.c=(double)c;
if((criteriaType!=null)| |(criteriaMaxCount!=null)| |(criteriaEps!=null))
{
var t=新的MCvTermCriteria((int)criteriaMaxCount,(double)criteriaEps);
if(criteriaType!=null)t.Type=(TermCriteriaType)criteriaType;
svm.term标准=t;
}
如果(p!=null)svm.p=(double)p;
如果(nu!=null)svm.nu=(double)nu;
if(!svm.Train(样本、DataLayoutType.RowSample、响应))
抛出新异常();
返回支持向量机;
}
私有静态void getTrainingData(字典类、out-Mat示例、out-Mat响应)
{
样本=空;
List LSTREP=新列表();
foreach(类中的int cls_mats.键)
{
整数计数=0;
foreach(类垫[cls]中的垫)
使用(变量描述=材料重塑(0,1))
{
if(samples==null)
样本=新垫(描述颜色,0,描述深度,1);
样品。回推(desc);
计数+=描述行;
}
for(int i=0;i        internal void Detect(IEnumerable<string> fileNames, Action<ShapeInfo> detected)
        {
            foreach (var fn in fileNames)
                using (Mat mat = getMat(fn, false))
                {
                    {
                        using (var samples = mat.Reshape(0, 1))
                        {
                            if (samples.Depth != DepthType.Cv32F)
                                samples.ConvertTo(samples, DepthType.Cv32F);
                            CvInvoke.Normalize(samples, samples, -1, 1, NormType.MinMax);
                            foreach (var svm in this.svms)
                            {
                                float p = svm.Predict(samples, null);

                            }
                        }
                    }
                }
        }