KD树 (k-Dimension tree)
来源:互联网 发布:淘宝申请全球购的条件 编辑:程序博客网 时间:2024/06/10 07:08
case class KDTree(left:KDTree,right:KDTree,point:Array[Int],direction:Int){
def isLeaf = left==null && right==null
def preOrder: Unit={
println(point.mkString(","))
if(left!=null) left.preOrder
if(right!=null) right.preOrder
}
}
def create(ps: Seq[Array[Int]], depth:Int):KDTree={
if(ps.isEmpty) return null
val numPoints = ps.size
val direction = depth % ps.head.length
val med = ps.sortBy(_(direction)).apply(numPoints/2)
val leftSeq = ps.filter(_(direction)<med(direction))
val rightSeq = ps.filter(_(direction)>med(direction))
new KDTree(create(leftSeq,depth+1), create(rightSeq,depth+1), med, direction)
}
val kdtree = KDTree.create(List(Array(2,3),Array(5,4),Array(4,7),Array(7,2),Array(9,6),Array(8,1)), 0)
kdtree.preOrder
case class Point(coo:Array[Int], label:Int)
case class KDTree(var left:KDTree,var right:KDTree,var points:Seq[Point],var direction:Int){
def this() = this(null,null,null,-1)
def isLeaf = left==null && right==null
def preOrder: Unit={
var list = List[KDTree]()
list ::= this
var tmp:KDTree = null
while(!list.isEmpty){
tmp = list.head
list = list.tail
println('('+tmp.points.map(_.label).mkString(",")+')')
if(tmp.right!=null) list ::= tmp.right
if(tmp.left!=null) list ::= tmp.left
}
}
}
object KDTree{
def create(ps: Seq[Point]):KDTree={
val dimension = ps.head.coo.length
val root = new KDTree
var list = List[(KDTree,Seq[Point])]((root, ps))
while(!list.isEmpty){
val (node, spoints) = list.head
list = list.tail
val n = spoints.size
var max = 0.0
for(i<-0 until dimension){
val (t1,t2) = spoints.map(_.coo(i)).map(x=>(x,x*x)).reduce((a,b)=>(a._1+b._1, a._2+b._2))
val tmp = (t2-t1*t1.toDouble/n)/n
if(max<=tmp){
max = tmp
node.direction = i
}
}
val sortedPoints = spoints.sortBy(_.coo(node.direction))
val med = sortedPoints(n/2).coo(node.direction)
val i1 = sortedPoints.indexWhere(_.coo(node.direction)==med)
val i2 = sortedPoints.indexWhere(_.coo(node.direction)!=med, i1+1)
node.points = sortedPoints.slice(i1, if(i2>0)i2 else n)
if(i1!=0){
val left = new KDTree
node.left = left
list = (left, sortedPoints.slice(0, i1))::list
}
if(i2<n && i2>0){
val right = new KDTree
node.right = right
list = (right, sortedPoints.slice(i2, n))::list
}
}
root
}
}
- KD-树(K-dimension tree)
- KD树 (k-Dimension tree)
- kd树(k-dimensional tree)(1)
- K相邻和Kd tree
- kd-tree和K近邻
- KD(kd tree)树介绍
- k近邻法中kd-tree树的创建
- k近邻算法(KNN)及kd树简介(KD-Tree)
- K近邻,kd树
- K近邻-kd树
- KD-Tree在K-NN的应用
- hdu4347 kd-tree询问k近点
- K-means KNN AND KD-tree
- KD-Tree k近点 HDU 4347
- [bzoj4520][kd-tree]K远点对
- 构造平衡kd树(kd tree)
- K近邻法、kd树
- 多维空间树 kd-tree
- 【跟我学apache-commons】【四】commons-io的使用
- HTTP请求和数据安全
- Ubuntu之旅——常用软件安装(一)
- SRVCC流程
- 关于编码风格
- KD树 (k-Dimension tree)
- hadoop自定义排序
- 06-图3 六度空间
- 网络访问之json数据解析
- Spring Web mvc Maven实现文件上传
- DButils工具类库的使用
- js encodeURIComponent()和encodeURI()区别
- Spring学习4--登录示例
- 算数-偶数和基数