public static float calculateSingleKernel(TrainingUnit xi, TrainingUnit xj,SVM ProblemSolution) { ProblemConfig problemConfig = ProblemSolution.ProblemCfg; // Vectors size check //if (xi.getDimension() != xj.getDimension()) return 0; // Linear: u'*v (inner product) if (problemConfig.kernelType == ProblemConfig.KernelType.Linear) { float sum = 0; for (int i = 0; i < xi.getDimension(); i++) { sum += xi.xVector[i] * xj.xVector[i]; } return sum; } // Radial basis function: exp(-gamma*|u-v|^2) if (problemConfig.kernelType == ProblemConfig.KernelType.RBF) { // Gamma is, by choice, 1 / (number of features). float sum = 0, temp; for (int i = 0; i < xi.getDimension(); i++) { temp = xi.xVector[i] - xj.xVector[i]; sum += temp * temp; } return (float)Math.Exp(-ProblemSolution.ProblemCfg.lambda * sum); } return 0; }
/// <summary>Adds a new training unit to the set</summary> /// <param name="newTrainingUnit">New training unit to add</param> public void addTrainingUnit(TrainingUnit newTrainingUnit) { if (p != 0) { if (p == newTrainingUnit.getDimension()) { trainingArray.Add(newTrainingUnit); } else { // Invalid entry, not equal in size to the others training units // Do nothing } } else // The first training set is being added { p = newTrainingUnit.getDimension(); trainingArray.Add(newTrainingUnit); } }