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

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

C语言实现SVM算法需要使用线性代数、数值优化等数学基础知识。以下是一个简单的SVM算法C语言实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <math.h> #define MAX_ITER 1000 // 最大迭代次数 #define EPS 0.001 // 精度 // 计算内积 double dot(double *x, double *y, int n) { double sum = 0; for (int i = 0; i < n; i++) { sum += x[i] * y[i]; } return sum; } // 计算向量的2范数 double norm2(double *x, int n) { double sum = 0; for (int i = 0; i < n; i++) { sum += x[i] * x[i]; } return sqrt(sum); } // 计算Hinge损失函数 double hinge_loss(double y, double f) { double loss = 1 - y * f; return loss > 0 ? loss : 0; } // 计算SVM的梯度 void svm_gradient(double **X, double *y, double *w, double *gradient, int n, int m, double C) { for (int i = 0; i < m; i++) { double f = dot(X[i], w, n); double loss = hinge_loss(y[i], f); for (int j = 0; j < n; j++) { gradient[j] += C * y[i] * X[i][j] * (loss > 0 ? -1 : 0); } } } // 计算SVM的目标函数值 double svm_objective(double **X, double *y, double *w, int n, int m, double C) { double obj = 0; for (int i = 0; i < m; i++) { double f = dot(X[i], w, n); obj += hinge_loss(y[i], f); } obj = C * obj / m; for (int i = 0; i < n; i++) { obj += w[i] * w[i] / 2; } return obj; } // 训练SVM模型 void svm_train(double **X, double *y, double *w, int n, int m, double C) { double *gradient = (double*)calloc(n, sizeof(double)); for (int iter = 0; iter < MAX_ITER; iter++) { svm_gradient(X, y, w, gradient, n, m, C); double step_size = 1.0 / (C * (iter + 1)); for (int i = 0; i < n; i++) { w[i] -= step_size * gradient[i]; } double obj = svm_objective(X, y, w, n, m, C); if (obj < EPS) { break; } } free(gradient); } int main() { // 生成样本数据 int m = 100; // 样本数 int n = 10; // 特征数 double **X = (double**)calloc(m, sizeof(double*)); for (int i = 0; i < m; i++) { X[i] = (double*)calloc(n, sizeof(double)); for (int j = 0; j < n; j++) { X[i][j] = (double)rand() / RAND_MAX * 2 - 1; } } double *y = (double*)calloc(m, sizeof(double)); for (int i = 0; i < m; i++) { y[i] = (dot(X[i], X[i], n) < 0.5) ? -1 : 1; } // 训练SVM模型 double *w = (double*)calloc(n, sizeof(double)); double C = 1.0; svm_train(X, y, w, n, m, C); // 输出模型参数 printf("w: [ "); for (int i = 0; i < n; i++) { printf("%lf ", w[i]); } printf("]\n"); // 释放内存 for (int i = 0; i < m; i++) { free(X[i]); } free(X); free(y); free(w); return 0; } ``` 在这个示例中,我们使用随机生成的样本数据进行训练,特征数为10,样本数为100。我们采用线性核函数,设置C参数为1。在训练过程中,我们使用梯度下降法来最小化SVM的目标函数。最终输出训练得到的模型参数w。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

亚丁号

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

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

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

打赏作者

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

抵扣说明:

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

余额充值
>