public override void Train(List <T> records) { HashSet <string> class_labels = new HashSet <string>(); foreach (T rec in records) { class_labels.Add(rec.Label); } mClassFieldLabels = class_labels.ToList(); mTheta.Clear(); int sample_count = records.Count; if (sample_count == 0) { throw new ArgumentException("sample_count==0"); } int dimension = records[0].Dimension; double[,] X = new double[sample_count, dimension]; int[] Y = new int[sample_count]; for (int i = 0; i < sample_count; ++i) { T rec = records[i]; for (int d = 0; d < dimension; ++d) { X[i, d] = rec[d]; } } double[] theta_0 = new double[dimension]; foreach (string class_label in mClassFieldLabels) { for (int i = 0; i < sample_count; ++i) { T rec = records[i]; Y[i] = rec.Label == class_label ? 1 : 0; } for (int d = 0; d < dimension; ++d) { theta_0[d] = 0; } LinearSVMCostFunction f = new LinearSVMCostFunction(X, Y, dimension, sample_count); f.C = mC; ContinuousSolution solution = mLocalSearcher.Minimize(theta_0, f, mMaxSolverIteration); mTheta[class_label] = solution.Values; } }
public override double ComputeCost(List <T> data_set) { int sample_count = data_set.Count; if (sample_count == 0) { return(-1); } int dimension = data_set[0].Dimension; double[,] X = new double[sample_count, dimension]; int[] Y = new int[sample_count]; for (int i = 0; i < sample_count; ++i) { T rec = data_set[i]; for (int d = 0; d < dimension; ++d) { X[i, d] = rec[d]; } } double total_error = 0; foreach (string class_label in mClassFieldLabels) { for (int i = 0; i < sample_count; ++i) { CDataRecord rec = data_set[i] as CDataRecord; Y[i] = rec.Label == class_label ? 1 : 0; } LinearSVMCostFunction f = new LinearSVMCostFunction(X, Y, dimension, sample_count); f.C = mC; double error = f.Evaluate(mTheta[class_label]); total_error += error; } return(total_error); }