Files
ai_academy/internal/application/service/metric/precision.go
T
runny 7ec21f35b0 chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
2026-11-16 18:12:23 +08:00

45 lines
1.2 KiB
Go

package metric
import (
"academy/internal/types"
)
// PrecisionMetric calculates precision for retrieval evaluation
type PrecisionMetric struct{}
// NewPrecisionMetric creates a new PrecisionMetric instance
func NewPrecisionMetric() *PrecisionMetric {
return &PrecisionMetric{}
}
// Compute calculates the precision score
func (r *PrecisionMetric) Compute(metricInput *types.MetricInput) float64 {
// Get ground truth and predicted IDs
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Convert ground truth to sets for efficient lookup
gtSets := SliceMap(gts, ToSet)
// Precision = retrieved items that are in ground truth / total retrieved items
// In the test cases, ground truth is a list of sets.
// We compute precision per ground truth set, and average them.
// But actually, precision is typically |retrieved ∩ relevant| / |retrieved|.
// Let's sum the precisions for each ground truth set and average them.
if len(gts) == 0 {
return 0.0
}
if len(ids) == 0 {
return 0.0
}
var totalPrecision float64
for _, gtSet := range gtSets {
hits := Hit(ids, gtSet)
totalPrecision += float64(hits) / float64(len(ids))
}
return totalPrecision / float64(len(gts))
}