实现支持向量机(SVM)算法的C#代码可以分为以下几个部分:数据准备、SVM模型训练和模型预测。下面是一个简单的示例,使用了基本的线性SVM实现。
1. 数据准备
首先,你需要一些示例数据。这里假设你已经有了一些二维数据,并且每个数据点都有一个标签(正类或负类)。
2. SVM类
下面是一个简单的线性SVM的实现:
using System;
using System.Collections.Generic;
using System.Linq;
public class SVM
{
private double learningRate;
private double regularizationParameter;
private List<double[]> supportVectors;
private List<int> supportVectorLabels;
private double bias;
private int maxIterations;
public SVM(double learningRate = 0.01, double regularizationParameter = 0.01, int maxIterations = 1000)
{
this.learningRate = learningRate;
this.regularizationParameter = regularizationParameter;
this.maxIterations = maxIterations;
this.supportVectors = new List<double[]>();
this.supportVectorLabels = new List<int>();
this.bias = 0;
}
public void Train(double[][] features, int[] labels)
{
int nSamples = features.Length;
int nFeatures = features[0].Length;
// 初始化权重
double[] weights = new double[nFeatures];
for (int iteration = 0; iteration < maxIterations; iteration++)
{
for (int i = 0; i < nSamples; i++)
{
// 计算预测
double prediction = Predict(features[i], weights);
// 检查是否需要更新
if (labels[i] * (prediction + bias) < 1)
{
// 更新权重和偏差
for (int j = 0; j < nFeatures; j++)
{
weights[j] += learningRate * (labels[i] * features[i][j] - regularizationParameter * weights[j]);
}
bias += learningRate * labels[i];
}
}
}
supportVectors.AddRange(features.Where((_, index) => labels[index] * (Predict(features[index], weights) + bias) < 1));
supportVectorLabels.AddRange(labels.Where((_, index) => labels[index] * (Predict(features[index], weights) + bias) < 1));
}
public int Predict(double[] feature)
{
double prediction = Predict(feature, supportVectors.Select(v => v).ToArray());
return prediction >= 0 ? 1 : -1;
}
private double Predict(double[] feature, double[] weights)
{
return weights.Zip(feature, (w, x) => w * x).Sum() + bias;
}
}
3. 使用示例
以下是如何使用这个SVM类的示例:
public class Program
{
public static void Main()
{
double[][] features = new double[][]
{
new double[] { 1.0, 2.0 },
new double[] { 2.0, 3.0 },
new double[] { 3.0, 3.5 },
new double[] { 5.0, 7.0 }
};
int[] labels = new int[] { -1, -1, 1, 1 };
SVM svm = new SVM();
svm.Train(features, labels);
double[] testSample = new double[] { 3.0, 4.0 };
int prediction = svm.Predict(testSample);
Console.WriteLine($"Prediction for test sample: {prediction}");
}
}
注意事项
- 这个实现是一个简单的线性SVM。如果需要更复杂的功能,比如使用核函数(如RBF),你可能需要实现额外的逻辑。
- 在实际应用中,你可能还需要实现数据标准化、交叉验证等功能来提高模型的性能。
这个代码示例为你提供了一个基础,之后可以根据需要进行扩展和优化!