本文整理汇总了C#中SVM.Problem类的典型用法代码示例。如果您正苦于以下问题:C# Problem类的具体用法?C# Problem怎么用?C# Problem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Problem类属于SVM命名空间,在下文中一共展示了Problem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例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();
//.........这里部分代码省略.........
示例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);
}
示例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();
}
示例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);
}
}
示例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);
}
}