Module_MachineLearning_zh - vorcyc/Vorcyc.Mathematics GitHub Wiki
当前位置 : [首页](HOME_zh)/[机器学习模块](Module_MachineLearning_zh)
因子分析、主成分分析 (PCA)、t-SNE 降维算法、独立成分分析 (ICA / FastICA) 盲源分离等。此外,还包括多种距离度量类。
| 子系统 | 命名空间 / 类型 | 说明 |
|---|---|---|
| 接口 |
IClassifier<T>、IRegressor<T>、IPreprocessor<T>
|
分类、回归、预处理统一契约 |
| 流水线 |
ClassificationPipeline<T>、RegressionPipeline<T>
|
预处理器链 + 模型 |
| 分类 |
Classfication.*、KnnClassifier、NumericDecisionTree、NumericRandomForest
|
Softmax、KNN、逻辑回归、OvR、GNB、数值树/森林 |
| 集成 |
AdaBoostClassifier<T>、GradientBoostingClassifier<T>
|
SAMME 决策桩、梯度提升多分类 |
| 回归 |
Regression.*、KnnRegressor
|
多元线性/岭回归、KNN 回归;MLR/MVR/KnnRegressor 实现 IBatchRegressor
|
| 预处理 | Preprocessing.* |
StandardScaler、MinMaxScaler、LabelEncoder、OneHotEncoder
|
| 评估 |
EvaluationMetrics、ClassificationMetrics
|
MSE/RMSE/准确率、混淆矩阵、P/R/F1 |
| 工具 |
DataSplit、CrossValidation、GridSearch、ModelBatchExtensions、IBatchClassifier / IBatchRegressor
|
划分、K 折 CV、网格搜索、批量预测 |
| 降维 |
DimensionalityReduction.LDA、PCA<TSelf>
|
LDA;PCA 样本外 Transform(0.10.18) |
| 源分离 | Decomposition.ICA |
FastICA 盲源分离(log-cosh / exp / cube,对称 / 逐次提取) |
| 序列化 | Serialization.ModelJsonPersistence |
Scaler / Softmax / Scaler 链 / kNN / RF / SVM / IsolationForest JSON 持久化(IF Save/Load:0.10.11) |
| 异常检测 | IsolationForest<T> |
Isolation Forest Fit + Score / Predict + CaptureSnapshot(持久化:0.10.11) |
分类流水线
using Vorcyc.Mathematics.MachineLearning.Classfication;
var pipeline = new ClassificationPipeline<double>()
.AddPreprocessor(new StandardScaler<double>())
.SetClassifier(new SoftmaxRegression<double>(learningRate: 0.1, epochs: 2000));
pipeline.Fit(xTrain, yTrain);
int label = pipeline.Predict(sample);回归流水线 + K 折交叉验证
using Vorcyc.Mathematics.MachineLearning.Regression;
IRegressor<double> model = new MultipleLinearRegression<double>();
var regPipe = new RegressionPipeline<double>()
.AddPreprocessor(new StandardScaler<double>())
.SetRegressor(model);
regPipe.Fit(x, y);
double[] yHat = regPipe.PredictBatch(x);
var cv = CrossValidation.ValidateRegressor(
x, y, folds: 5, seed: 1,
buildPredictor: (xTr, yTr) =>
{
var m = new MultivariateRidgeRegression<double>(0.01);
m.Fit(xTr, yTr);
return s => m.Predict(s);
});AdaBoost / 梯度提升
var ada = new AdaBoostClassifier<double>(nEstimators: 50);
ada.Fit(xTrain, yTrain);
var gbt = new GradientBoostingClassifier<double>(nEstimators: 50, learningRate: 0.1, maxDepth: 3);
gbt.Fit(xTrain, yTrain);以下示例使用二维数值特征与整数类别标签(0、1、2),与 Examples/MachineLearning_example 及 TESTS/ML_module_test 中的用法一致。所有分类器均实现 IClassifier<T>,统一调用 Fit(x, y) / Predict(sample)。
# 运行完整分类演示(默认)
dotnet run --project Examples/MachineLearning_example
# 回归流水线演示
dotnet run --project Examples/MachineLearning_example -- regression数据划分
using Vorcyc.Mathematics.MachineLearning;
// x: [样本数, 特征数],y: 整数类别
double[,] x = { /* ... */ };
int[] y = { /* ... */ };
var (xTrain, yTrain, xTest, yTest) = DataSplit.TrainTestSplit(x, y, testRatio: 0.25, seed: 7);数值决策树 / 随机森林
var tree = new NumericDecisionTree<double>(maxDepth: 8);
tree.Fit(xTrain, yTrain);
int label = tree.Predict([2.1, 1.8]);
var forest = new NumericRandomForest<double>(
numTrees: 80, maxFeatures: 2, maxDepth: 10, seed: 11);
forest.Fit(xTrain, yTrain);
label = forest.Predict([2.1, 1.8]);高斯朴素贝叶斯 / KNN
using Vorcyc.Mathematics.MachineLearning.Classfication;
var gnb = new GaussianNaiveBayes<double>();
gnb.Fit(xTrain, yTrain);
label = gnb.Predict([2.1, 1.8]);
// 各类别后验概率(字典:类别 → 概率)
var posteriors = gnb.PredictProbabilities([2.1, 1.8]);
var knn = new KnnClassifier<double>(k: 3);
knn.Fit(xTrain, yTrain);
label = knn.Predict([2.1, 1.8]);
var knnReg = new KnnRegressor<double>(k: 3);
knnReg.Fit(xTrainReg, yTrainReg);
double yHat = knnReg.Predict(sample);
double[] yBatch = knnReg.PredictBatch(xTestReg);Softmax / 逻辑回归 / One-vs-Rest
using Vorcyc.Mathematics.MachineLearning.Classfication;
var softmax = new SoftmaxRegression<double>(learningRate: 0.1, epochs: 2500);
softmax.Fit(xTrain, yTrain);
label = softmax.Predict([2.1, 1.8]);
// 二分类(标签须为 0 或 1)
var logit = new LogisticRegression<double>(learningRate: 0.05, epochs: 2000);
logit.Fit(xTrainBinary, yTrainBinary);
// 多分类:内部为每个类别训练一个二分类器
var ovr = new OneVsRestClassifier<double>(learningRate: 0.1, epochs: 2500);
ovr.Fit(xTrain, yTrain);
label = ovr.Predict([2.1, 1.8]);评估指标
// 批量预测(实现 IBatchClassifier 的模型走优化路径:树/森林、GNB、KNN、Softmax、Logistic、OvR、流水线等)
int[] predictions = forest.PredictBatch(xTest);
// 或:var predictions = ModelBatchExtensions.PredictBatch(anyClassifier, xTest);
double accuracy = EvaluationMetrics.Accuracy(yTest, predictions);
var cm = ClassificationMetrics.ConfusionMatrix(yTest, predictions);
double macroF1 = ClassificationMetrics.MacroF1(cm);
double microF1 = ClassificationMetrics.MicroF1(cm);
double precision0 = ClassificationMetrics.Precision(cm, classLabel: 0);Softmax / Logistic mini-batch 训练
using Vorcyc.Mathematics.MachineLearning.Classfication;
var softmax = new SoftmaxRegression<double>(
learningRate: 0.1, epochs: 2000, batchSize: 32, seed: 42);
softmax.Fit(xTrain, yTrain);
var logit = new LogisticRegression<double>(
learningRate: 0.05, epochs: 2000, batchSize: 32, seed: 42);
logit.Fit(xTrainBinary, yTrainBinary);K 折交叉验证
var cv = CrossValidation.Validate(
x, y,
folds: 5,
seed: 21,
buildPredictor: (xTr, yTr) =>
{
var model = new GaussianNaiveBayes<double>();
model.Fit(xTr, yTr);
return sample => model.Predict(sample);
});
Console.WriteLine($"准确率: {cv.MeanAccuracy:P1} ± {cv.StdAccuracy:P1}");
Console.WriteLine($"Macro-F1: {cv.MeanMacroF1:F3} ± {cv.StdMacroF1:F3}");网格搜索(超参数)
using Vorcyc.Mathematics.MachineLearning.Classfication;
var candidates = new[]
{
new { Epochs = 1000, Lr = 0.05 },
new { Epochs = 2000, Lr = 0.10 }
};
var result = GridSearch.SearchClassifier(
x, y,
candidates,
opt => new SoftmaxRegression<double>(learningRate: opt.Lr, epochs: opt.Epochs),
folds: 3,
seed: 5);
// 用最佳超参在全量数据上重训
var bestOpts = result.BestOptions;
var bestModel = new SoftmaxRegression<double>(learningRate: bestOpts.Lr, epochs: bestOpts.Epochs);
bestModel.Fit(x, y);
label = bestModel.Predict([2.1, 1.8]);JSON 持久化(Scaler + Softmax + kNN / RF / SVM,0.10.10)
using Vorcyc.Mathematics.MachineLearning.Classfication;
using Vorcyc.Mathematics.MachineLearning.Preprocessing;
using Vorcyc.Mathematics.MachineLearning.Serialization;
var scaler = new StandardScaler<double>();
scaler.Fit(xTrain);
ModelJsonPersistence.SaveStandardScaler(scaler, "scaler.json");
var xScaled = scaler.Transform(xTrain);
var model = new SoftmaxRegression<double>(learningRate: 0.1, epochs: 2000);
model.Fit(xScaled, yTrain);
ModelJsonPersistence.SaveSoftmaxRegression(model, "softmax.json");
// 加载后推理
var loadedScaler = ModelJsonPersistence.LoadStandardScaler("scaler.json");
var loadedModel = ModelJsonPersistence.LoadSoftmaxRegression("softmax.json");
label = loadedModel.Predict(loadedScaler.Transform([2.1, 1.8]));
// 另有(0.10.10):Save/LoadStandardScalerChain、Save/LoadKnnClassifier、
// Save/LoadNumericRandomForest、Save/LoadSupportVectorMachine
// 另有(0.10.11):Save/LoadIsolationForest高斯过程预测标准差(0.10.10)
using Vorcyc.Mathematics.MachineLearning.CurveFitting;
var gpr = CurveFitter<float>.GaussianProcess(xs, ys, lengthScale: 1f, signalVariance: 1f, noiseVariance: 0.01f);
float mean = gpr.PredictMean(xStar); // 或 gpr.Predict(xStar)
float std = gpr.PredictStd(xStar); // 置信带:mean ± k * std
float var = gpr.PredictVariance(xStar);0.10.17:经典
CurveFitter(线性 / 多项式 / 指数 / 对数 / 幂 / 正弦 / 样条 / LOWESS / 移动平均 / 非线性 / 贝叶斯)增加可选CancellationToken。GPR 原先已支持。三次样条Predict改为二分查找。
0.10.16:
CurveFitter多项式 / 指数 / 对数 / 幂的Fit_SIMD将stackalloc移出热循环复用,避免大 N(约 ≥5×10⁵)在 Auto/Simd 下StackOverflow。线性回归 SIMD 不受影响。
Isolation Forest 异常打分(0.10.10)+ JSON 快照(0.10.11)
using Vorcyc.Mathematics.MachineLearning;
using Vorcyc.Mathematics.MachineLearning.Serialization;
var forest = new IsolationForest<float>(numTrees: 100, subsampleSize: 256, seed: 42);
forest.Fit(featureMatrix); // 行 = 样本
float[] scores = forest.Score(featureMatrix); // 越高越异常
int[] flags = forest.Predict(featureMatrix, threshold: 0.6f); // 1 = 异常
ModelJsonPersistence.SaveIsolationForest(forest, "iforest.json"); // 0.10.11
var loaded = ModelJsonPersistence.LoadIsolationForest("iforest.json");线性判别分析(LDA)
using Vorcyc.Mathematics.MachineLearning.DimensionalityReduction;
var lda = new LinearDiscriminantAnalysis<double>(numComponents: 1);
lda.Fit(x, y);
label = lda.Predict([2.1, 1.8]);
var projected = lda.Transform([2.1, 1.8]); // 降维后的特征大多数模型都接受可选的 ComputingContext? context 构造参数,并/或提供可写的 Context 属性,可按模型、按作用域或全进程粒度启用 SIMD/并行 CPU 执行。解析顺序为 显式 context → ComputingScope → ComputingContext.Default;null 表示「未指定」(仍沿用上述链路),并非「强制标量」。预设与阈值参见 ComputingContext 模块。
已并行化的范围
| 范围 | 类型 | 并行工作 |
|---|---|---|
| 批量预测 |
LogisticRegression、SoftmaxRegression、GaussianNaiveBayes、OneVsRestClassifier、NumericDecisionTree、NumericRandomForest、KnnClassifier、KnnRegressor、MultipleLinearRegression、MultivariateRidgeRegression、ClassificationPipeline、RegressionPipeline
|
PredictBatch 按行并行(经 IBatchClassifier / IBatchRegressor) |
| 训练 / 拟合 |
GradientBoostingClassifier、OneVsRestClassifier、NumericRandomForest
|
按类 / 按树拟合 |
| 聚类 |
KMeansClusterer、ExpectationMaximization / GMM、DBSCAN、HierarchicalClustering、VectorQuantization
|
分配 / E 步 / 邻域 / 连接计算 |
| 降维与源分离 |
PCA、LinearDiscriminantAnalysis、FactorAnalysis、TSNE、Decomposition.ICA
|
协方差 / 投影 / 亲和度 / 白化计算 |
| 指标与辅助 |
ClassificationMetrics.ConfusionMatrix(..., context)、ModelBatchExtensions.PredictBatch(..., context)
|
直方图 / 泛型批量预测 |
| 曲线拟合 |
CurveFitter<T>(Linear … Power、Sinusoidal、CubicSpline、LocallyWeighted、MovingAverage、GaussianProcess、Nonlinear、BayesianLinear) |
可选 computingContext;与 Statistics 同构的 Normal / Simd / Parallel 分发(见 ComputingContext);GaussianProcess 接受 CancellationToken(0.10.9),返回带 PredictStd / PredictVariance 的 GaussianProcessFitResult(0.10.10) |
每个并行核都只写入互不相交的索引并使用线程本地的暂存缓冲区,因此并行结果与串行路径完全一致(见 TESTS/ML_module_test)。
AdaBoostClassifier与SupportVectorMachine为保持 API 一致接受context并暴露Context,但其当前拟合/预测仍为串行执行(保留以备未来并行化)。
using Vorcyc.Mathematics; // ComputingContext, ComputingScope
using Vorcyc.Mathematics.MachineLearning;
// 1) 按模型:在模型实例上设置策略
var forest = new NumericRandomForest<double>(numTrees: 80, maxFeatures: 2, maxDepth: 10, seed: 11)
{
Context = ComputingContext.Parallel
};
forest.Fit(xTrain, yTrain);
int[] predictions = forest.PredictBatch(xTest); // 批量预测按行并行
// 2) 按作用域:保持 Context 未设置(null),一次性管控多个操作
var knn = new KnnClassifier<double>(k: 3);
knn.Fit(xTrain, yTrain);
using (ComputingScope.Enter(ComputingContext.Parallel))
{
int[] p = knn.PredictBatch(xTest); // 遵循作用域
var cm = ClassificationMetrics.ConfusionMatrix(yTest, p); // 遵循作用域
}对实现
IBatchClassifier/IBatchRegressor的模型,由实例的Context管控PredictBatch;ModelBatchExtensions.PredictBatch的context参数仅作用于其他分类器使用的泛型回退路径。
以下类型位于
Vorcyc.Mathematics.MachineLearning命名空间及其子命名空间(.Regression、.Classfication、.Clustering、.DimensionalityReduction、.Decomposition、.Distances、.Preprocessing、.Serialization、.CurveFitting)。
📒目录
- 🔖 0.9 分类器完整示例
- 🔖 ComputingContext 集成(并行执行)
- 🔖 Vorcyc.Mathematics.MachineLearning.KNN<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.MultipleLinearRegression<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.SimpleLinearRegression<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.SupportVectorMachine<TSelf> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.DBSCAN<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.ExpectationMaximization<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.GMM<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.HierarchicalClustering<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.KMeansClusterer<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Clustering.VectorQuantization<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.FactorAnalysis<T> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.PCA<TSelf> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.Decomposition.ICA<TSelf> 类
- 🔖 Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.TSNE<T> 类
- 🔖 距离度量类
KNN<T> 用于增量式 K 近邻回归(Add / Regress / RegressBatch);矩阵训练请使用 KnnRegressor<T>(IRegressor + IBatchRegressor)。分类请使用 KnnClassifier<T>。
-
public MachineLearningTask Task { get; }- 固定为
MachineLearningTask.Regression。
- 固定为
-
public KNN(ComputingContext? context = null)- 初始化 KNN 类的新实例。
- 参数:
-
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public void Add(Point<T> point, T target)/Add(ReadOnlySpan<T> features, T target)- 添加回归样本。
-
public T Regress(Point<T> point, int k)/Regress(ReadOnlySpan<T> features, int k, bool distanceWeighted = false)- 对特征向量进行 K 近邻回归;可选距离加权平均。
-
public T[] RegressBatch(T[,] x, int k, bool distanceWeighted = false)- 对特征矩阵的每一行进行批量 K 近邻回归;每行返回一个预测值。
-
public void RegressBatch(T[,] x, int k, Span<T> predictions, bool distanceWeighted = false)- 将批量 K 近邻回归的预测结果写入提供的 span。
using Vorcyc.Mathematics.MachineLearning;
using Vorcyc.Mathematics.Numerics;
var knn = new KNN<double>();
knn.Add(new Point<double>(1.0, 0.0), 2.0);
knn.Add(new Point<double>(2.0, 0.0), 4.0);
knn.Add(new Point<double>(3.0, 0.0), 6.0);
double y = knn.Regress(new Point<double>(2.5, 0.0), k: 2);
// 分类
var clf = new KnnClassifier<double>(k: 3);
clf.Fit(xTrain, yTrain);
int label = clf.Predict(sample);Vorcyc.Mathematics.MachineLearning.MultipleLinearRegression<T> 是一个用于对数据集进行多元线性回归的类。正规方程在正定情形下优先使用 Cholesky 分解求解(LinearEquationSolver.CholeskySolve),否则回退 LU。
-
public IReadOnlyList<T> Coefficients { get; }- 获取回归模型的回归系数。
-
public T Intercept { get; }- 获取回归模型的截距。
-
public T RSquared { get; }- 获取决定系数 R²。
-
public ComputingContext? Context { get; set; }- 批量预测所遵循的执行策略;为 null 时使用环境作用域或默认上下文。
-
public MachineLearningTask Task { get; }- 获取多元线性回归的任务类型,支持回归。
-
public void Fit(T[,] x, T[] y)- 拟合多元线性回归模型的回归系数和截距。
- 参数:
-
x: 自变量矩阵。 -
y: 因变量向量。
-
-
public T Predict(T[] x)- 根据给定的自变量和回归系数预测因变量的值。
- 参数:
-
x: 自变量。
-
- 返回值: 预测的因变量值。
以下是一个使用 MultipleLinearRegression<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning;
using Vorcyc.Mathematics.MachineLearning.Regression;
public class MultipleLinearRegressionExample
{
public static void Main()
{
// 定义自变量矩阵
double[,] x = new double[,] { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 } };
// 定义因变量向量
double[] y = new double[] { 2, 3, 5, 7, 11 };
// 创建多元线性回归实例
var regression = new MultipleLinearRegression<double>();
regression.Fit(x, y);
// 输出回归模型的截距和回归系数
Console.WriteLine("Intercept: " + regression.Intercept);
Console.WriteLine("Coefficients:");
for (int i = 0; i < regression.Coefficients.Count; i++)
{
Console.WriteLine("Coefficient " + (i + 1) + ": " + regression.Coefficients[i]);
}
// 预测新输入的因变量值
double[] newInput = new double[] { 6, 7 };
double prediction = regression.Predict(newInput);
Console.WriteLine("Predicted value for input " + string.Join(", ", newInput) + ": " + prediction);
}
}Vorcyc.Mathematics.MachineLearning.SimpleLinearRegression<T> 是一个用于一元线性回归的类。
-
public T Slope { get; }- 获取线性回归模型的斜率。
-
public T Intercept { get; }- 获取线性回归模型的截距。
-
public T RSquared { get; }- 获取决定系数 R²。
-
public ComputingContext? Context { get; set; }-
PredictBatch所遵循的执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public MachineLearningTask Task { get; }- 获取一元线性回归的任务类型,支持回归。
-
public (T slope, T intercept) Fit(Point<T>[] data)- 计算线性回归模型的斜率和截距。
- 参数:
-
data: 包含数据点的数组。
-
- 返回值: 返回一个元组,包含斜率和截距。
-
public (T slope, T intercept) Fit(Span<T> x, Span<T> y)- 计算线性回归模型的斜率和截距。
- 参数:
-
x: 自变量的数组。 -
y: 因变量的数组。
-
- 返回值: 返回一个元组,包含斜率和截距。
-
public T GetX(T y)- 根据给定的 y 值、斜率和截距计算 x 值。
- 参数:
-
y: 因变量的值。
-
- 返回值: 返回计算得到的 x 值。
-
public T GetY(T x)- 根据给定的 x 值、斜率和截距计算 y 值。
- 参数:
-
x: 自变量的值。
-
- 返回值: 返回计算得到的 y 值。
-
public T[] PredictBatch(Span<T> x, ComputingContext? context = null)- 对一批 x 值预测 y;遵循
Context以启用 SIMD/并行执行。 - 参数:
-
x: 要计算的自变量值。 -
context: 可选执行策略,覆盖Context。
-
- 返回值: 预测的 y 值数组,每个
x元素对应一个。
- 对一批 x 值预测 y;遵循
以下是一个使用 SimpleLinearRegression<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning;
using Vorcyc.Mathematics.MachineLearning.Regression;
using Vorcyc.Mathematics.Numerics;
using static System.Runtime.InteropServices.JavaScript.JSType;
public class SimpleLinearRegressionExample
{
public static void Main()
{
// 定义数据点
var data = new Point<double>[] { new Point<double>(1.0, 2.0), new Point<double>(2.0, 3.0), new Point<double>(3.0, 5.0), new Point<double>(4.0, 4.0), new Point<double>(5.0, 6.0) };
// 创建一元线性回归实例
var regression = new SimpleLinearRegression<double>();
var (slope, intercept) = regression.Fit(data);
// 输出回归模型的斜率和截距
Console.WriteLine($"Slope: {slope}, Intercept: {intercept}");
// 预测新输入的 y 值
var x = 6.0;
var y = regression.GetY(x);
Console.WriteLine($"For x = {x}, predicted y = {y}");
}
}Vorcyc.Mathematics.MachineLearning.SupportVectorMachine<TSelf> 是一个简单的线性支持向量机(SVM)实现,支持选择核函数。
-
public MachineLearningTask Task { get; }- 获取支持向量机的任务类型,支持分类和回归。
-
public SupportVectorMachine(int featureCount, TSelf? learningRate = null, int epochs = 1000, SupportVectorMachineKernelType kernelType = SupportVectorMachineKernelType.Linear, TSelf? gamma = null, int polynomialDegree = 3, TSelf? sigmoidAlpha = null, TSelf? sigmoidConstant = null, ComputingContext? context = null)- 初始化 SupportVectorMachine 类的新实例。
- 参数:
-
featureCount: 输入数据的特征数量。 -
learningRate: 训练算法的学习率。为 null 时默认为 0.01。 -
epochs: 训练的轮数。 -
kernelType: 核函数类型。默认为线性核函数。取值:Linear、Polynomial、Gaussian、RBF、DotProduct、Sigmoid。 -
gamma: 核函数 gamma;为 null 时默认为 1.0(用于多项式 / 高斯 / RBF)。 -
polynomialDegree: 多项式核的阶数;默认 3。 -
sigmoidAlpha: Sigmoid 核的 alpha;为 null 时默认为 0.01。 -
sigmoidConstant: Sigmoid 核的常数;为 null 时默认为 1.0。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public void Train(TSelf[][] inputs, int[] outputs)- 使用提供的训练数据训练 SVM。
- 参数:
-
inputs: 输入数据,每个元素是一个特征值数组。 -
outputs: 与输入数据对应的输出标签。
-
-
public int Predict(Span<TSelf> input)- 预测给定输入数据的类别标签。
- 参数:
-
input: 输入数据,一个特征值数组。
-
- 返回值: 预测的类别标签(1 或 -1)。
-
private TSelf PredictRaw(TSelf[] input)- 计算给定输入数据的原始预测值。
- 参数:
-
input: 输入数据,一个特征值数组。
-
- 返回值: 原始预测值。
-
private Func<TSelf[], TSelf[], TSelf> GetKernelFunction(SupportVectorMachineKernelType kernelType)- 获取指定类型的核函数。
- 参数:
-
kernelType: 核函数类型。
-
- 返回值: 核函数的委托。
-
private static TSelf LinearKernel(TSelf[] x, TSelf[] y)- 线性核函数。
- 参数:
-
x: 第一个输入向量。 -
y: 第二个输入向量。
-
- 返回值: 核函数的计算结果。
-
private static TSelf PolynomialKernel(TSelf[] x, TSelf[] y)- 多项式核函数。
- 参数:
-
x: 第一个输入向量。 -
y: 第二个输入向量。
-
- 返回值: 核函数的计算结果。
-
private static TSelf GaussianKernel(TSelf[] x, TSelf[] y)- 高斯核函数(RBF)。
- 参数:
-
x: 第一个输入向量。 -
y: 第二个输入向量。
-
- 返回值: 核函数的计算结果。
-
private static TSelf SigmoidKernel(TSelf[] x, TSelf[] y)- Sigmoid 核函数。
- 参数:
-
x: 第一个输入向量。 -
y: 第二个输入向量。
-
- 返回值: 核函数的计算结果。
以下是一个使用 SupportVectorMachine<TSelf> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning;
public class SupportVectorMachineExample
{
public static void Main()
{
// 定义训练数据
double[][] inputs = new double[][] { new double[] { 1.0, 2.0 }, new double[] { 2.0, 3.0 }, new double[] { 3.0, 3.0 }, new double[] { 6.0, 5.0 }, new double[] { 7.0, 8.0 } };
int[] outputs = new int[] { 1, 1, -1, -1, 1 };
// 创建支持向量机实例
var svm = new SupportVectorMachine<double>(2);
// 训练支持向量机
svm.Train(inputs, outputs);
// 预测新输入的类别标签
double[] newInput = new double[] { 4.0, 4.0 };
int prediction = svm.Predict(newInput);
Console.WriteLine($"Prediction for input {string.Join(", ", newInput)}: {prediction}");
}
}Vorcyc.Mathematics.MachineLearning.Clustering.DBSCAN<T> 是一个用于二维平面点的 DBSCAN 聚类算法类。
-
public MachineLearningTask Task { get; }- 获取 DBSCAN 的任务类型,支持聚类。
-
public DBSCAN(Point<T>[] points, T eps, int minPts, ComputingContext? context = null)- 使用指定的点、邻域半径和最小点数初始化 DBSCAN 类的新实例。
- 参数:
-
points: 要聚类的点。 -
eps: 邻域半径。 -
minPts: 形成一个聚类的最小点数。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public List<List<Point<T>>> Cluster()- 执行 DBSCAN 聚类。
- 返回值: 聚类的列表,每个聚类是一个点的列表。
-
private void ExpandCluster(Point<T> point, List<Point<T>> neighbors, List<Point<T>> cluster)- 扩展聚类。
- 参数:
-
point: 当前点。 -
neighbors: 当前点的邻居。 -
cluster: 当前聚类。
-
-
private List<Point<T>> GetNeighbors(Point<T> point)- 获取点的邻居。
- 参数:
-
point: 当前点。
-
- 返回值: 邻居的列表。
以下是一个使用 DBSCAN<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using System.Collections.Generic;
using Vorcyc.Mathematics.MachineLearning.Clustering;
using Vorcyc.Mathematics.Numerics;
public class DBSCANExample
{
public static void Main()
{
// 定义点
var points = new Point<double>[] { new Point<double>(1.0, 2.0), new Point<double>(2.0, 2.0), new Point<double>(2.0, 3.0), new Point<double>(8.0, 7.0), new Point<double>(8.0, 8.0), new Point<double>(25.0, 80.0) };
// 创建 DBSCAN 实例
var dbscan = new DBSCAN<double>(points, 3.0, 2);
// 执行聚类
var clusters = dbscan.Cluster();
// 输出聚类结果
for (int i = 0; i < clusters.Count; i++)
{
Console.WriteLine($"Cluster {i + 1}:");
foreach (var point in clusters[i])
{
Console.WriteLine($"({point.X}, {point.Y})");
}
}
}
}Vorcyc.Mathematics.MachineLearning.Clustering.ExpectationMaximization<T> 是一个用于实现期望最大化(EM)算法的类。
-
public IReadOnlyList<T[]> Means { get; }- 获取聚类中心(均值)。
-
public IReadOnlyList<Matrix<T>> Covariances { get; }- 获取协方差矩阵。
-
public IReadOnlyList<T> Weights { get; }- 获取权重。
-
public MachineLearningTask Task { get; }- 获取期望最大化算法的任务类型,支持聚类。
-
public ExpectationMaximization(int numClusters)- 初始化 ExpectationMaximization 类的新实例。
- 参数:
-
numClusters: 聚类的数量。
-
-
public void Fit(List<T[]> data, int maxIterations = 100, T tolerance = default)- 使用期望最大化算法拟合数据。
- 参数:
-
data: 要拟合的数据,表示为数组的列表。 -
maxIterations: 最大迭代次数;默认 100。 -
tolerance: 收敛容差;为default时默认 1e-4。
-
-
public int Predict(T[] dataPoint)- 预测数据点所属的聚类。
- 参数:
-
dataPoint: 要预测的数据点。
-
- 返回值: 数据点所属聚类的索引。
以下是一个使用 ExpectationMaximization<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using System.Collections.Generic;
using Vorcyc.Mathematics.MachineLearning.Clustering;
public class ExpectationMaximizationExample
{
public static void Main()
{
// 定义数据点
var data = new List<double[]>
{
new double[] { 1.0, 2.0 },
new double[] { 2.0, 2.0 },
new double[] { 2.0, 3.0 },
new double[] { 8.0, 7.0 },
new double[] { 8.0, 8.0 },
new double[] { 25.0, 80.0 }
};
// 创建期望最大化实例
var em = new ExpectationMaximization<double>(2);
// 拟合数据
em.Fit(data);
// 输出聚类中心
Console.WriteLine("Cluster Centers (Means):");
foreach (var mean in em.Means)
{
Console.WriteLine($"({string.Join(", ", mean)})");
}
// 输出协方差矩阵
Console.WriteLine("Covariance Matrices:");
foreach (var covariance in em.Covariances)
{
for (int i = 0; i < covariance.Rows; i++)
{
for (int j = 0; j < covariance.Columns; j++)
{
Console.Write($"{covariance[i, j]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
// 输出权重
Console.WriteLine("Weights:");
foreach (var weight in em.Weights)
{
Console.WriteLine(weight);
}
}
}Vorcyc.Mathematics.MachineLearning.Clustering.GMM<T> 是一个用于实现高斯混合模型(GMM)的类。
-
public IReadOnlyList<T[]> Means { get; }- 获取聚类中心(均值)。
-
public IReadOnlyList<Matrix<T>> Covariances { get; }- 获取协方差矩阵。
-
public IReadOnlyList<T> Weights { get; }- 获取权重。
-
public MachineLearningTask Task { get; }- 获取高斯混合模型的任务类型,支持聚类。
-
public GMM(int numComponents, int maxIterations = 100, T tolerance = default, ComputingContext? context = null)- 初始化 GMM 类的新实例。
- 参数:
-
numComponents: 高斯分布的数量。 -
maxIterations: 最大迭代次数。 -
tolerance: 对数似然函数的收敛容差;为default时默认 1e-6。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public void Fit(List<T[]> data)- 使用高斯混合模型拟合数据。
- 参数:
-
data: 要拟合的数据,表示为数组的列表。
-
-
public int Predict(T[] dataPoint)- 预测数据点所属的聚类。
- 参数:
-
dataPoint: 要预测的数据点。
-
- 返回值: 数据点所属聚类的索引。
以下是一个使用 GMM<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using System.Collections.Generic;
using Vorcyc.Mathematics.MachineLearning.Clustering;
public class GMMExample
{
public static void Main()
{
// 定义数据点
var data = new List<double[]>
{
new double[] { 1.0, 2.0 },
new double[] { 2.0, 2.0 },
new double[] { 2.0, 3.0 },
new double[] { 8.0, 7.0 },
new double[] { 8.0, 8.0 },
new double[] { 25.0, 80.0 }
};
// 创建高斯混合模型实例
var gmm = new GMM<double>(2);
// 拟合数据
gmm.Fit(data);
// 输出聚类中心
Console.WriteLine("Cluster Centers (Means):");
foreach (var mean in gmm.Means)
{
Console.WriteLine($"({string.Join(", ", mean)})");
}
// 输出协方差矩阵
Console.WriteLine("Covariance Matrices:");
foreach (var covariance in gmm.Covariances)
{
for (int i = 0; i < covariance.Rows; i++)
{
for (int j = 0; j < covariance.Columns; j++)
{
Console.Write($"{covariance[i, j]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
// 输出权重
Console.WriteLine("Weights:");
foreach (var weight in gmm.Weights)
{
Console.WriteLine(weight);
}
}
}Vorcyc.Mathematics.MachineLearning.Clustering.HierarchicalClustering<T> 是一个用于二维平面点的层次聚类算法类。
-
public MachineLearningTask Task { get; }- 获取层次聚类的任务类型,支持聚类。
-
public HierarchicalClustering(Point<T>[] points, ComputingContext? context = null)- 使用指定的点初始化 HierarchicalClustering 类的新实例。
- 参数:
-
points: 要聚类的点。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public List<List<Point<T>>> Cluster(int k)- 对点执行层次聚类,直到达到指定数量的聚类。
- 参数:
-
k: 所需的聚类数量。
-
- 返回值: 聚类的列表,每个聚类是一个点的列表。
-
private (int cluster1, int cluster2, T minDistance) FindClosestClusters()- 查找最接近的两个聚类。
- 返回值: 最接近的两个聚类的索引和它们之间的距离。
-
private T AverageLinkage(List<Point<T>> cluster1, List<Point<T>> cluster2)- 计算两个聚类之间的平均连接距离。
- 参数:
-
cluster1: 第一个聚类。 -
cluster2: 第二个聚类。
-
- 返回值: 两个聚类之间的平均连接距离。
-
private T Distance(Point<T> a, Point<T> b)- 计算两个点之间的欧几里得距离。
- 参数:
-
a: 第一个点。 -
b: 第二个点。
-
- 返回值: 两个点之间的欧几里得距离。
以下是一个使用 HierarchicalClustering<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using System.Collections.Generic;
using Vorcyc.Mathematics.MachineLearning.Clustering;
using Vorcyc.Mathematics.Numerics;
public class HierarchicalClusteringExample
{
public static void Main()
{
// 定义点
var points = new Point<double>[]
{
new Point<double>(1.0, 2.0),
new Point<double>(2.0, 2.0),
new Point<double>(2.0, 3.0),
new Point<double>(8.0, 7.0),
new Point<double>(8.0, 8.0),
new Point<double>(25.0, 80.0)
};
// 创建层次聚类实例
var hierarchicalClustering = new HierarchicalClustering<double>(points);
// 执行聚类
var clusters = hierarchicalClustering.Cluster(2);
// 输出聚类结果
for (int i = 0; i < clusters.Count; i++)
{
Console.WriteLine($"Cluster {i + 1}:");
foreach (var point in clusters[i])
{
Console.WriteLine($"({point.X}, {point.Y})");
}
}
}
}Vorcyc.Mathematics.MachineLearning.Clustering.KMeansClusterer<T> 是一个用于实现 K 均值聚类算法的类。
-
public MachineLearningTask Task { get; }- 获取 K 均值聚类的任务类型,支持聚类。
-
public KMeansClusterer(T[][] data, int numClusters, int maxIterations, T tolerance, ComputingContext? context = null)- 使用指定的数据、聚类数量、最大迭代次数和收敛容忍度初始化 KMeansClusterer 类的新实例。
- 参数:
-
data: 要聚类的数据。 -
numClusters: 要创建的聚类数量。 -
maxIterations: 最大迭代次数。 -
tolerance: 收敛容忍度。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public int[] Cluster()- 执行 K 均值聚类算法。
- 返回值: 每个数据点的聚类分配。
-
private int[] InitClustering(int numData, int numClusters)- 初始化聚类。
- 参数:
-
numData: 数据的数量。 -
numClusters: 聚类的数量。
-
- 返回值: 初始化的聚类分配。
-
private T[][] Allocate(int numRows, int numCols)- 分配二维数组的空间。
- 参数:
-
numRows: 行数。 -
numCols: 列数。
-
- 返回值: 分配的二维数组。
-
private bool UpdateCentroids()- 更新质心(聚类中心)。
- 返回值: 是否成功更新质心。
-
private bool UpdateClustering()- 更新聚类分配。
- 返回值: 是否成功更新聚类分配。
-
private T Distance(T[] vector1, T[] vector2)- 计算两个向量之间的欧几里得距离。
- 参数:
-
vector1: 第一个向量。 -
vector2: 第二个向量。
-
- 返回值: 两个向量之间的欧几里得距离。
-
private int MinIndex(T[] distances)- 找到数组中最小值的索引。
- 参数:
-
distances: 表示距离的数组。
-
- 返回值: 最小值的索引。
以下是一个使用 KMeansClusterer<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning.Clustering;
public class KMeansClustererExample
{
public static void Main()
{
// 定义数据点
var data = new double[][]
{
new double[] { 1.0, 2.0 },
new double[] { 2.0, 2.0 },
new double[] { 2.0, 3.0 },
new double[] { 8.0, 7.0 },
new double[] { 8.0, 8.0 },
new double[] { 25.0, 80.0 }
};
// 创建 KMeansClusterer 实例
var kMeans = new KMeansClusterer<double>(data, 2, 100, 1e-6);
// 执行聚类
var clustering = kMeans.Cluster();
// 输出聚类结果
for (int i = 0; i < clustering.Length; i++)
{
Console.WriteLine($"Data point {i + 1} is in cluster {clustering[i] + 1}");
}
}
}Vorcyc.Mathematics.MachineLearning.Clustering.VectorQuantization<T> 是一个用于实现矢量量化算法的类。
-
public IReadOnlyList<T[]> Codebook { get; }- 获取码书。
-
public MachineLearningTask Task { get; }- 获取矢量量化的任务类型,支持聚类。
-
public VectorQuantization(int codebookSize, int dimensions)- 初始化 VectorQuantization 类的新实例。
- 参数:
-
codebookSize: 码书的大小。 -
dimensions: 矢量的维度。
-
-
public List<T> Train(IEnumerable<T[]> data, int maxIterations = 100)- 训练矢量量化模型。
- 参数:
-
data: 训练数据,包含多个矢量(每个为一个数组)。 -
maxIterations: 最大迭代次数。
-
- 返回值: 每次迭代的误差列表。
-
public T[] Predict(T[] vector)- 根据输入矢量找到最近的码矢量。
- 参数:
-
vector: 输入矢量。
-
- 返回值: 最近的码矢量。
-
public void SaveCodebook(string filePath)- 将码书保存到文件中。
- 参数:
-
filePath: 文件路径。
-
-
public void LoadCodebook(string filePath)- 从文件中加载码书。
- 参数:
-
filePath: 文件路径。
-
以下是一个使用 VectorQuantization<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using System.Collections.Generic;
using Vorcyc.Mathematics.MachineLearning.Clustering;
using Vorcyc.Mathematics.LinearAlgebra;
using System.Numerics;
public class VectorQuantizationExample
{
public static void Main()
{
// 定义数据点
var data = new List<double[]>
{
new double[] { 1.0, 2.0 },
new double[] { 2.0, 2.0 },
new double[] { 2.0, 3.0 },
new double[] { 8.0, 7.0 },
new double[] { 8.0, 8.0 },
new double[] { 25.0, 80.0 }
};
// 创建矢量量化实例
var vq = new VectorQuantization<double>(2, 2);
// 训练模型
var errors = vq.Train(data);
// 输出训练误差
Console.WriteLine("Training Errors:");
foreach (var error in errors)
{
Console.WriteLine(error);
}
// 预测新矢量
var newVector = new double[] { 3.0, 3.0 };
var nearestCodeVector = vq.Predict(newVector);
Console.WriteLine($"Nearest code vector to ({string.Join(", ", newVector)}): ({string.Join(", ", nearestCodeVector)})");
// 保存码书
vq.SaveCodebook("codebook.json");
// 加载码书
vq.LoadCodebook("codebook.json");
}
}Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.FactorAnalysis<T> 是一个用于执行因子分析的类。
-
public Matrix<T> Loadings { get; private set; }- 获取因子载荷矩阵。
-
public T[] Communalities { get; private set; }- 获取共同性数组。
-
public T[] SpecificVariances { get; private set; }- 获取特异性方差数组。
-
public MachineLearningTask Task { get; }- 获取因子分析的任务类型,支持降维。
-
public FactorAnalysis(ComputingContext? context = null)- 初始化 FactorAnalysis 类的新实例。
- 参数:
-
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public void Analyze(Matrix<T> data, int numFactors)- 执行因子分析。
- 参数:
-
data: 数据矩阵,每行代表一个样本,每列代表一个变量。 -
numFactors: 因子数量。
-
以下是一个使用 FactorAnalysis<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning.DimensionalityReduction;
using Vorcyc.Mathematics.LinearAlgebra;
public class FactorAnalysisExample
{
public static void Main()
{
// 定义数据矩阵
var data = new Matrix<double>(
new double[,]
{
{ 1.0, 2.0, 3.0 },
{ 2.0, 3.0, 4.0 },
{ 3.0, 4.0, 5.0 },
{ 4.0, 5.0, 6.0 },
{ 5.0, 6.0, 7.0 }
});
// 创建因子分析实例
var factorAnalysis = new FactorAnalysis<double>();
// 执行因子分析
factorAnalysis.Analyze(data, 2);
// 输出因子载荷矩阵
Console.WriteLine("Factor Loadings:");
for (int i = 0; i < factorAnalysis.Loadings.Rows; i++)
{
for (int j = 0; j < factorAnalysis.Loadings.Columns; j++)
{
Console.Write($"{factorAnalysis.Loadings[i, j]} ");
}
Console.WriteLine();
}
// 输出共同性数组
Console.WriteLine("Communalities:");
foreach (var communality in factorAnalysis.Communalities)
{
Console.WriteLine(communality);
}
// 输出特异性方差数组
Console.WriteLine("Specific Variances:");
foreach (var specificVariance in factorAnalysis.SpecificVariances)
{
Console.WriteLine(specificVariance);
}
}
}Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.PCA<TSelf> 是一个用于降维和特征提取的主成分分析 (PCA) 类。
-
public MachineLearningTask Task { get; }- 获取 PCA 的任务类型,支持降维。
-
public TSelf[] Means { get; }- 拟合时的逐特征均值,用于中心化训练与样本外行。
-
public TSelf[] Eigenvalues { get; }- 协方差特征值,已按降序排列。
-
public TSelf[][] Eigenvectors { get; }- 主轴;下标
j对应第j个主成分。
- 主轴;下标
-
public PCA(TSelf[,] data, ComputingContext? context = null)- 初始化 PCA 类的新实例。
- 参数:
-
data: 输入数据集,每行是一个样本,每列是一个特征。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public TSelf[,] Transform()- 将(已中心化的)训练数据转换为主成分。
- 返回值: 转换后的主成分数据。
-
public TSelf[,] Transform(TSelf[,] x, int? components = null)- 用拟合均值中心化
x,再投影到前components个主轴(为 null 时用全部)。
- 用拟合均值中心化
-
public TSelf[] GetExplainedVarianceRatio()- 获取解释的方差比例。
- 返回值: 解释的方差比例数组。
以下是一个使用 PCA<TSelf> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning.DimensionalityReduction;
public class PCAExample
{
public static void Main()
{
// 定义数据矩阵
var data = new double[,]
{
{ 1.0, 2.0, 3.0 },
{ 2.0, 3.0, 4.0 },
{ 3.0, 4.0, 5.0 },
{ 4.0, 5.0, 6.0 },
{ 5.0, 6.0, 7.0 }
};
// 创建 PCA 实例
var pca = new PCA<double>(data);
// 转换数据
var transformedData = pca.Transform();
// 输出转换后的数据
Console.WriteLine("Transformed Data:");
for (int i = 0; i < transformedData.GetLength(0); i++)
{
for (int j = 0; j < transformedData.GetLength(1); j++)
{
Console.Write($"{transformedData[i, j]} ");
}
Console.WriteLine();
}
// 输出解释的方差比例
var explainedVarianceRatio = pca.GetExplainedVarianceRatio();
Console.WriteLine("Explained Variance Ratio:");
foreach (var ratio in explainedVarianceRatio)
{
Console.WriteLine(ratio);
}
}
}Vorcyc.Mathematics.MachineLearning.Decomposition.ICA<TSelf> 是一个使用 FastICA 算法进行盲源分离的独立成分分析 (ICA) 类:它从若干线性混合信号中恢复统计独立、非高斯的源信号(恢复结果在尺度和排列顺序上存在不确定性)。输入布局与 PCA 相同:每行是一个样本(随时间的观测),每列是一路观测到的混合信号。
它支持三种对比(非线性)函数和两种估计策略:
-
ICANonlinearity:LogCosh(默认,g(u) = tanh(alpha * u))、Exp(g(u) = u * exp(-u^2 / 2),对离群点 / 强超高斯源更稳健)、Cube(g(u) = u^3,速度快但对离群点更敏感)。 -
ICAAlgorithm:Symmetric(默认,使用对称去相关并行估计所有成分)、Deflation(使用 Gram-Schmidt 逐次提取每个成分)。
-
public MachineLearningTask Task { get; }- 获取任务类型,返回
MachineLearningTask.SourceSeparation。
- 获取任务类型,返回
-
public int NumberOfComponents { get; }- 提取的独立成分数量。
-
public ICANonlinearity Nonlinearity { get; }- 估计时使用的对比函数。
-
public ICAAlgorithm Algorithm { get; }- 使用的估计策略(对称或逐次提取)。
-
public bool HasConverged { get; }- 不动点迭代是否在迭代上限内收敛。
-
public int Iterations { get; }- 实际执行的迭代次数。
-
public TSelf[] Mean { get; }- 中心化时去除的逐特征均值的副本。
-
public ICA(TSelf[,] data, int? numberOfComponents = null, ICANonlinearity nonlinearity = ICANonlinearity.LogCosh, ICAAlgorithm algorithm = ICAAlgorithm.Symmetric, int maxIterations = 200, double tolerance = 1e-4, double alpha = 1.0, int? randomSeed = null, ComputingContext? context = null)- 初始化 ICA 实例并运行 FastICA。
- 参数:
-
data: 输入数据集(每行是一个样本,每列是一路观测信号)。 -
numberOfComponents: 要提取的成分数量(默认等于输入信号的列数)。 -
nonlinearity: 对比函数(LogCosh/Exp/Cube)。 -
algorithm: 估计策略(Symmetric/Deflation)。 -
maxIterations: 最大不动点迭代次数。 -
tolerance: 解混矩阵变化量的收敛容差。 -
alpha: log-cosh 对比函数的斜率(通常取 [1, 2]);其他非线性会忽略该参数。 -
randomSeed: 用于可复现初始化的可选随机种子。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public TSelf[,] Transform()- 返回恢复出的源信号。
- 返回值:
[样本数, 成分数]的估计源矩阵。
-
public TSelf[,] InverseTransform(TSelf[,] sources)- 使用混合矩阵从源信号重建观测信号。
- 返回值:
[样本数, 特征数]的重建观测矩阵。
-
public TSelf[,] GetMixingMatrix()- 获取估计的混合矩阵
A(观测 = A * 源)。 - 返回值:
[特征数, 成分数]矩阵。
- 获取估计的混合矩阵
-
public TSelf[,] GetUnmixingMatrix()- 获取估计的解混矩阵
W(源 = W * 中心化观测)。 - 返回值:
[成分数, 特征数]矩阵。
- 获取估计的解混矩阵
以下示例使用 FastICA 分离两路混合源信号:
using System;
using Vorcyc.Mathematics.MachineLearning.Decomposition;
public class ICAExample
{
public static void Main()
{
int n = 2000;
var data = new double[n, 2];
for (int t = 0; t < n; t++)
{
double s1 = Math.Sin(t * 0.02); // 正弦源
double s2 = Math.Sign(Math.Sin(t * 0.047)); // 方波源
// 两路独立源的线性混合。
data[t, 0] = 0.60 * s1 + 0.40 * s2;
data[t, 1] = 0.35 * s1 + 0.75 * s2;
}
// 使用 exp 非线性 + 逐次提取(默认是 LogCosh + 对称)。
var ica = new ICA<double>(
data,
nonlinearity: ICANonlinearity.Exp,
algorithm: ICAAlgorithm.Deflation,
randomSeed: 7);
var sources = ica.Transform(); // [n, 2] 恢复出的独立源
Console.WriteLine($"Converged: {ica.HasConverged}, Iterations: {ica.Iterations}");
Console.WriteLine($"Components: {ica.NumberOfComponents}");
}
}Vorcyc.Mathematics.MachineLearning.DimensionalityReduction.TSNE<T> 是一个用于降维和数据可视化的 t-SNE 算法类。
无公开属性。
-
public TSNE(int perplexity = 30, int maxIter = 1000, T learningRate = default, Action<int, T>? progressCallback = null, ComputingContext? context = null)- 初始化 TSNE 类的新实例。
- 参数:
-
perplexity: 困惑度参数。 -
maxIter: 最大迭代次数。 -
learningRate: 学习率;为default时默认200.0。 -
progressCallback: 可选进度回调,参数为(迭代次数, 代价)。 -
context: 可选执行策略;为 null 时使用环境作用域或默认上下文。
-
-
public Matrix<T> FitTransform(Matrix<T> data)- 执行 t-SNE 算法并返回降维后的矩阵。
- 参数:
-
data: 输入的高维数据矩阵。
-
- 返回值: 降维后的矩阵。
以下是一个使用 TSNE<T> 类中多个方法的示例,并在示例中加入了注释:
using System;
using Vorcyc.Mathematics.MachineLearning.DimensionalityReduction;
using Vorcyc.Mathematics.LinearAlgebra;
public class TSNEExample
{
public static void Main()
{
// 定义数据矩阵
var data = new Matrix<double>(
new double[,]
{
{ 1.0, 2.0, 3.0 },
{ 2.0, 3.0, 4.0 },
{ 3.0, 4.0, 5.0 },
{ 4.0, 5.0, 6.0 },
{ 5.0, 6.0, 7.0 }
});
// 创建 t-SNE 实例
var tsne = new TSNE<double>();
// 执行 t-SNE 算法
var transformedData = tsne.FitTransform(data);
// 输出降维后的数据
Console.WriteLine("Transformed Data:");
for (int i = 0; i < transformedData.Rows; i++)
{
for (int j = 0; j < transformedData.Columns; j++)
{
Console.Write($"{transformedData[i, j]} ");
}
Console.WriteLine();
}
}
}Angular 距离,或 Cosine 距离的正确度量版本。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
ArgMax 距离(L0 距离)。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Bray-Curtis 距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Canberra 距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Chebyshev 距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Cosine 距离。对于正确的距离度量,请参见 Angular 距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
Dice 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
欧几里得距离度量。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
汉明距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Hellinger 距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Jaccard(指数)距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
Kulczynski 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Levenshtein 距离。
-
public double Distance(string x, string y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
曼哈顿(也称为 Taxicab 或 L1)距离。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Matching 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Minkowski 距离是一个在范数向量空间中的度量,可以看作是欧几里得距离和曼哈顿距离的推广。
-
public static TNumber Order { get; set; }- 获取或设置此 Minkowski 距离的阶数
p。
- 获取或设置此 Minkowski 距离的阶数
-
public static TNumber Distance(TNumber[] x, TNumber[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Pearson 相关性相似度。
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 计算点
x和y之间的相似度。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
- 计算点
Rogers-Tanimoto 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Russel-Rao 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Sokal-Michener 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
Sokal-Sneath 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
加权欧几里得距离和相似度。返回 Sqrt(Σ wᵢ·(xᵢ−yᵢ)²),即标准的加权欧几里得度量。
-
public static TSelf[] Weights { get; set; }- 获取或设置每个维度的权重。默认值是一个全为 1 的向量。
-
public static void SetDimensions(int dimensions)- 将 Weights 设置为指定维度的全 1 向量。
- 参数:
-
dimensions: 数据集中的维度(列)数。
-
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
加权平方欧几里得距离和相似度。请注意,此距离不是度量,因为它不遵守三角不等式。
-
public TSelf[] Weights { get; set; }- 获取或设置每个维度的权重。默认值是一个全为 1 的向量。
-
public static void SetDimensions(int dimensions)- 将 Weights 设置为指定维度的全 1 向量。
- 参数:
-
dimensions: 数据集中的维度(列)数。
-
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static TSelf Similarity(TSelf[] x, TSelf[] y)- 获取两个点之间的相似度。
- 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间相似度的值。
Yule 不相似度。
-
public static TSelf Distance(TSelf[] x, TSelf[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的值。
- 计算点
-
public static double Distance(int[] x, int[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的双精度值。
- 计算点
-
public static float Distance(float[] x, float[] y)- 计算点
x和y之间的距离。 - 参数:
-
x: 第一个点。 -
y: 第二个点。
-
- 返回值: 表示
x和y之间距离的单精度值。
- 计算点