4 Star 7 Fork 4

ShirDon-廖显东/零基础Go语言算法实战源码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
interview13-7.go 2.21 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2024-04-22 14:56 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础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
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助