Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Hiểu về Logistic Regression trong C#

Logistic Regression - mô hình phân loại nhị phân (binary classification), dự đoán xác suất P(y=1|x). Dùng trong y tế, marketing, risk scoring.

Cơ sở toán học

Sigmoid function: σ(z) = 1 / (1 + e^(-z))

Linear combination: z = w₁x₁ + w₂x₂ + ... + wₙxₙ + b

Dự đoán: ŷ = 1 if σ(z) ≥ 0.5 else 0

Triển khai từ đầu (Educational)

using System;
using System.Linq;

public class LogisticRegression
{
    private double[] _weights;
    private double _bias;
    private readonly double _learningRate;
    private readonly int _epochs;
    
    public LogisticRegression(int features, double lr = 0.01, int epochs = 1000)
    {
        _weights = new double[features];
        _learningRate = lr;
        _epochs = epochs;
    }
    
    private double Sigmoid(double z) => 1.0 / (1.0 + Math.Exp(-z));
    
    public void Fit(double[][] X, int[] y)
    {
        int n = X.Length;
        int m = X[0].Length;
        
        for (int epoch = 0; epoch < _epochs; epoch++)
        {
            for (int i = 0; i < n; i++)
            {
                double z = _bias;
                for (int j = 0; j < m; j++) z += _weights[j] * X[i][j];
                
                double pred = Sigmoid(z);
                double error = y[i] - pred;
                
                _bias += _learningRate * error;
                for (int j = 0; j < m; j++)
                    _weights[j] += _learningRate * error * X[i][j];
            }
        }
    }
    
    public int Predict(double[] x)
    {
        double z = _bias;
        for (int j = 0; j < _weights.Length; j++) z += _weights[j] * x[j];
        return Sigmoid(z) >= 0.5 ? 1 : 0;
    }
    
    public double PredictProba(double[] x)
    {
        double z = _bias;
        for (int j = 0; j < _weights.Length; j++) z += _weights[j] * x[j];
        return Sigmoid(z);
    }
}

// Sử dụng
class Program
{
    static void Main()
    {
        // Dữ liệu mẫu: [feature1, feature2] -> label
        double[][] X = { 
            new[] { 1.0, 2.0 }, new[] { 2.0, 3.0 }, new[] { 3.0, 1.0 },
            new[] { 5.0, 5.0 }, new[] { 6.0, 4.0 }, new[] { 7.0, 6.0 }
        };
        int[] y = { 0, 0, 0, 1, 1, 1 };
        
        var model = new LogisticRegression(2, 0.1, 1000);
        model.Fit(X, y);
        
        Console.WriteLine($"Weights: [{string.Join(", ", model.GetWeights())}]");
        Console.WriteLine($"Bias: {model.GetBias()}");
        
        double[] test = { 4.0, 4.0 };
        Console.WriteLine($"Test {string.Join(", ", test)}: Prob={model.PredictProba(test):F3}, Class={model.Predict(test)}");
    }
}

Thư viện ML thực tế

  • ML.NET - Microsoft ML framework cho .NET
  • Accord.NET - Thư viện ML classiques
  • TensorFlow.NET / ONNX Runtime - Deep learning

Lưu ý: Code trên chỉ để hiểu nguyên lý. Production dùng ML.NET: mlContext.BinaryClassification.Trainers.SdcaLogisticRegression().