C#语言实现支持向量机 (Support Vector Machine, SVM)算法

实现支持向量机(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),你可能需要实现额外的逻辑。
  • 在实际应用中,你可能还需要实现数据标准化、交叉验证等功能来提高模型的性能。

这个代码示例为你提供了一个基础,之后可以根据需要进行扩展和优化!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚丁号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值