Julia机器学习--KNN算法BallTree 结构分类统计,并使用圆绘制图表

NearestNeighbors是Julia中一个效率比较高的KNN分类统计代码库,它提供了BallTree,KDTree等多种数据结构。

这里使用BallTree结构,并绘制图表。这里仍然使用鸢尾花数据

代码示例

using RDatasets
using DataFrames
using CSV
using NearestNeighbors
using Colors
using PyPlot
using PyCall
import PyPlot:plot
import NearestNeighbors.HyperSphere
@pyimport matplotlib.patches as patch
# y = load("D:/leaning/Julia/pkg-other/Rdatasets/csv/datasets/iris.csv") |> DataFrame

iris = dataset("datasets", "iris"); # load the data
# iris = DataFrame(CSV.File(joinpath(dirname(pathof(DataFrames)),"D:/leaning/Julia/pkg-other/Rdatasets/csv/datasets/iris.csv")));
show(iris)
iris[:, 1:4]
features = collect(Matrix(iris[:, 1:4])'); # features to use for clustering

tree = BallTree(features, Euclidean(); leafsize = 50)


# 跳过非叶子节点
offset = tree.tree_data.n_internal_nodes + 1
nleafs = tree.tree_data.n_leafs

# 叶子节点的范围
index_range = offset: offset + nleafs - 1

# 生成颜色图谱
cols = distinguishable_colors(length(index_range), RGB(0,0,0))

# 创建图片
cfig = figure()
ax = cfig[:add_subplot](1,1,1)
ax[:set_aspect]("equal")
axis((2.5,9.0,1.0,5.0))

# 坐标上添加一个圆
function add_sphere(ax, hs::HyperSphere, col)
    ell = patch.Circle(hs.center, radius = hs.r, facecolor="none", edgecolor=col)
    ax[:add_artist](ell)
end


for (i, idx) = enumerate(index_range)
    col = cols[i]
    # 获取决策树中的叶子节点
    range = NearestNeighbors.get_leaf_range(tree.tree_data, idx)
    d = tree.data[range]
    for idex in 1:length(d)
        point = collect(d[idex])
        # 先画点
        plot(vec(point[1,:]), vec(point[2,:]), "*", color = (col.r, col.g, col.b))
    end
    # 设置圆
    sphere = tree.hyper_spheres[idx]
    add_sphere(ax, sphere, (col.r, col.g, col.b))
end

title("Leaf nodes with their corresponding points")
cfig[:savefig]("iris.png")

绘制的图表

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

October-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值