287 lines
9.2 KiB
C#
287 lines
9.2 KiB
C#
#nullable enable
|
||
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
|
||
namespace PLCSharp.VVMs.Vision.GalleryClassifier
|
||
{
|
||
/// <summary>
|
||
/// 特征向量画廊 —— 管理 OK/NG 特征向量库,支持即时追加/删除,零重训。
|
||
///
|
||
/// 用法:
|
||
/// var gallery = new FeatureGallery(512); // 特征维度
|
||
/// gallery.AddOk(feature); // 点击"训练OK"
|
||
/// gallery.AddNg(feature); // 点击"训练NG"
|
||
/// var result = gallery.Classify(feature); // 推理
|
||
/// </summary>
|
||
public class FeatureGallery
|
||
{
|
||
private readonly int _dimension;
|
||
private readonly List<float[]> _okVectors = [];
|
||
private readonly List<float[]> _ngVectors = [];
|
||
private readonly object _lock = new();
|
||
|
||
/// <summary>OK 库样本数</summary>
|
||
public int OkCount
|
||
{ get { lock (_lock) return _okVectors.Count; } }
|
||
|
||
/// <summary>NG 库样本数</summary>
|
||
public int NgCount
|
||
{ get { lock (_lock) return _ngVectors.Count; } }
|
||
|
||
/// <param name="dimension">特征向量维度(必须与 ONNX 模型输出一致)</param>
|
||
public FeatureGallery(int dimension)
|
||
{
|
||
_dimension = dimension > 0 ? dimension : throw new ArgumentException("维度必须大于 0");
|
||
}
|
||
|
||
#region 增删
|
||
|
||
public void AddOk(float[] feature)
|
||
{
|
||
ValidateFeature(feature);
|
||
lock (_lock) _okVectors.Add(feature);
|
||
}
|
||
|
||
public void AddNg(float[] feature)
|
||
{
|
||
ValidateFeature(feature);
|
||
lock (_lock) _ngVectors.Add(feature);
|
||
}
|
||
|
||
/// <summary>从 OK 库删除第 index 条</summary>
|
||
public void RemoveOkAt(int index)
|
||
{
|
||
lock (_lock)
|
||
{
|
||
if (index >= 0 && index < _okVectors.Count)
|
||
_okVectors.RemoveAt(index);
|
||
}
|
||
}
|
||
|
||
/// <summary>从 NG 库删除第 index 条</summary>
|
||
public void RemoveNgAt(int index)
|
||
{
|
||
lock (_lock)
|
||
{
|
||
if (index >= 0 && index < _ngVectors.Count)
|
||
_ngVectors.RemoveAt(index);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从两个库中删除与目标向量最接近的样本(用于纠正误判时精确删除)
|
||
/// </summary>
|
||
/// <param name="feature">被误判的样本特征</param>
|
||
/// <param name="fromOk">true=从OK库删, false=从NG库删</param>
|
||
/// <returns>是否成功删除</returns>
|
||
public bool RemoveNearest(float[] feature, bool fromOk)
|
||
{
|
||
ValidateFeature(feature);
|
||
lock (_lock)
|
||
{
|
||
var list = fromOk ? _okVectors : _ngVectors;
|
||
if (list.Count == 0) return false;
|
||
|
||
int nearestIdx = 0;
|
||
float minDist = float.MaxValue;
|
||
for (int i = 0; i < list.Count; i++)
|
||
{
|
||
float d = L2Distance(feature, list[i]);
|
||
if (d < minDist) { minDist = d; nearestIdx = i; }
|
||
}
|
||
list.RemoveAt(nearestIdx);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/// <summary>清空所有库</summary>
|
||
public void Clear()
|
||
{
|
||
lock (_lock)
|
||
{
|
||
_okVectors.Clear();
|
||
_ngVectors.Clear();
|
||
}
|
||
}
|
||
|
||
/// <summary>清空 OK 库</summary>
|
||
public void ClearOk()
|
||
{
|
||
lock (_lock) _okVectors.Clear();
|
||
}
|
||
|
||
/// <summary>清空 NG 库</summary>
|
||
public void ClearNg()
|
||
{
|
||
lock (_lock) _ngVectors.Clear();
|
||
}
|
||
|
||
#endregion 增删
|
||
|
||
#region 序列化(保存/加载画廊数据)
|
||
|
||
/// <summary>导出为可序列化的传输对象</summary>
|
||
public GalleryData Export()
|
||
{
|
||
lock (_lock)
|
||
{
|
||
return new GalleryData
|
||
{
|
||
Dimension = _dimension,
|
||
OkVectors = _okVectors.Select(v => (float[])v.Clone()).ToList(),
|
||
NgVectors = _ngVectors.Select(v => (float[])v.Clone()).ToList()
|
||
};
|
||
}
|
||
}
|
||
|
||
/// <summary>从传输对象导入</summary>
|
||
public void Import(GalleryData data)
|
||
{
|
||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||
if (data.Dimension != _dimension)
|
||
throw new ArgumentException($"维度不匹配:期望 {_dimension},数据 {data.Dimension}");
|
||
|
||
lock (_lock)
|
||
{
|
||
_okVectors.Clear();
|
||
_ngVectors.Clear();
|
||
foreach (var v in data.OkVectors) _okVectors.Add(v);
|
||
foreach (var v in data.NgVectors) _ngVectors.Add(v);
|
||
}
|
||
}
|
||
|
||
#endregion 序列化(保存/加载画廊数据)
|
||
|
||
#region 分类决策
|
||
|
||
/// <summary>
|
||
/// 分类结果
|
||
/// </summary>
|
||
public readonly struct ClassificationResult
|
||
{
|
||
/// <summary>true=OK, false=NG</summary>
|
||
public readonly bool IsOk;
|
||
|
||
/// <summary>到OK库最近距离(越小越像OK)</summary>
|
||
public readonly float OkDistance;
|
||
|
||
/// <summary>到NG库最近距离(越小越像NG)</summary>
|
||
public readonly float NgDistance;
|
||
|
||
/// <summary>OK距离 - NG距离,负值偏向OK,正值偏向NG</summary>
|
||
public readonly float Delta;
|
||
|
||
public ClassificationResult(bool isOk, float okDist, float ngDist)
|
||
{
|
||
IsOk = isOk;
|
||
OkDistance = okDist;
|
||
NgDistance = ngDist;
|
||
Delta = okDist - ngDist;
|
||
}
|
||
|
||
/// <summary>OK 置信度 [0,1],仅作参考不严格概率意义</summary>
|
||
public float OkConfidence => (OkDistance + NgDistance) < 1e-10f ? 0.5f
|
||
: NgDistance / (OkDistance + NgDistance);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 对输入特征进行分类决策。
|
||
/// 比较到 OK 库和 NG 库的最短 L2 距离,选更近的一方。
|
||
/// </summary>
|
||
public ClassificationResult Classify(float[] feature)
|
||
{
|
||
ValidateFeature(feature);
|
||
|
||
lock (_lock)
|
||
{
|
||
bool hasOk = _okVectors.Count > 0;
|
||
bool hasNg = _ngVectors.Count > 0;
|
||
|
||
// 只有一个库有样本时,退化为单类异常检测
|
||
if (!hasOk && !hasNg)
|
||
return new ClassificationResult(true, float.MaxValue, float.MaxValue);
|
||
if (!hasOk)
|
||
return new ClassificationResult(false, float.MaxValue, MinDistance(feature, _ngVectors));
|
||
if (!hasNg)
|
||
return new ClassificationResult(true, MinDistance(feature, _okVectors), float.MaxValue);
|
||
|
||
float okDist = MinDistance(feature, _okVectors);
|
||
float ngDist = MinDistance(feature, _ngVectors);
|
||
|
||
return new ClassificationResult(okDist <= ngDist, okDist, ngDist);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取 TopK 近邻信息(用于调试/可视化)
|
||
/// </summary>
|
||
public (float[] okDists, float[] ngDists) TopKDistances(float[] feature, int k)
|
||
{
|
||
ValidateFeature(feature);
|
||
lock (_lock)
|
||
{
|
||
var okDists = _okVectors.Select(v => L2Distance(feature, v)).OrderBy(d => d).Take(k).ToArray();
|
||
var ngDists = _ngVectors.Select(v => L2Distance(feature, v)).OrderBy(d => d).Take(k).ToArray();
|
||
return (okDists, ngDists);
|
||
}
|
||
}
|
||
|
||
#endregion 分类决策
|
||
|
||
#region 内部
|
||
|
||
private void ValidateFeature(float[] feature)
|
||
{
|
||
if (feature == null)
|
||
throw new ArgumentNullException(nameof(feature));
|
||
if (feature.Length != _dimension)
|
||
throw new ArgumentException($"特征维度应为 {_dimension},实际 {feature.Length}");
|
||
}
|
||
|
||
private static float MinDistance(float[] a, List<float[]> vectors)
|
||
{
|
||
float min = float.MaxValue;
|
||
foreach (var v in vectors)
|
||
{
|
||
float d = L2Distance(a, v);
|
||
if (d < min) min = d;
|
||
}
|
||
return min;
|
||
}
|
||
|
||
private static float L2Distance(float[] a, float[] b)
|
||
{
|
||
float sum = 0f;
|
||
for (int i = 0; i < a.Length; i++)
|
||
{
|
||
float diff = a[i] - b[i];
|
||
sum += diff * diff;
|
||
}
|
||
return MathF.Sqrt(sum);
|
||
}
|
||
|
||
#endregion 内部
|
||
}
|
||
|
||
#region 序列化传输对象
|
||
|
||
/// <summary>
|
||
/// 画廊数据的可序列化传输对象。
|
||
/// 可用 System.Text.Json / Newtonsoft.Json 直接序列化保存到文件。
|
||
/// </summary>
|
||
public class GalleryData
|
||
{
|
||
/// <summary>特征维度</summary>
|
||
public int Dimension { get; set; }
|
||
|
||
/// <summary>OK 特征向量列表</summary>
|
||
public List<float[]> OkVectors { get; set; } = [];
|
||
|
||
/// <summary>NG 特征向量列表</summary>
|
||
public List<float[]> NgVectors { get; set; } = [];
|
||
}
|
||
|
||
#endregion 序列化传输对象
|
||
} |