代码拉取完成,页面将自动刷新
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import (
"fmt"
"math"
)
// 表示具有特征和类标签的数据点
type DataPoint struct {
features []float64
label string
}
// 计算两个数据点之间的欧氏距离
func euclideanDistance(p1, p2 DataPoint) float64 {
var sumSquares float64
for i := range p1.features {
diff := p1.features[i] - p2.features[i]
sumSquares += diff * diff
}
return math.Sqrt(sumSquares)
}
// 根据 k 最近邻点对新数据点进行分类
func kNNClassify(k int, trainingSet []DataPoint, newPoint DataPoint) string {
// 计算新点与训练集中所有点之间的距离
distances := make([]float64, len(trainingSet))
for i, point := range trainingSet {
distances[i] = euclideanDistance(point, newPoint)
}
// 找到 k 最近邻点的索引
indices := make([]int, k)
for i := range indices {
minIndex := 0
for j := range distances {
if distances[j] < distances[minIndex] {
minIndex = j
}
}
indices[i] = minIndex
distances[minIndex] = math.MaxFloat64
}
// 计算 k 最近邻点的类标签
counts := make(map[string]int)
for _, index := range indices {
counts[trainingSet[index].label]++
}
// 确定 k 最近邻点中的多数类标签
var (
maxCount int
maxLabel string
)
for label, count := range counts {
if count > maxCount {
maxCount = count
maxLabel = label
}
}
return maxLabel
}
func main() {
// 创建具有特征和类标签的数据点训练集
trainingSet := []DataPoint{
{[]float64{2.0, 4.0}, "A"},
{[]float64{4.0, 2.0}, "A"},
{[]float64{4.0, 4.0}, "B"},
{[]float64{4.0, 6.0}, "B"},
{[]float64{6.0, 4.0}, "B"},
}
// 创建一个新的数据点进行分类
newPoint := DataPoint{[]float64{6.0, 6.0}, ""}
// 使用 KNN 算法对新数据点进行分类
k := 3
label := kNNClassify(k, trainingSet, newPoint)
fmt.Printf("新点属于类:%s\n", label)
}
//$ go run interview10-15.go
//新点属于类:B
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。