R中的Knn回归 [英] Knn Regression in R

查看:654
本文介绍了R中的Knn回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Knn回归方法以及后来的内核平滑. 我希望使用R中的图来演示这些方法.我已经使用以下代码生成了数据集:

I am investigating Knn regression methods and later Kernel Smoothing. I wish to demonstrate these methods using plots in R. I have generated a data set using the following code:

x = runif(100,0,pi)
e = rnorm(100,0,0.1)
y = sin(x)+e

我一直在尝试按照9.2中有关如何使用"knn.reg"的说明进行操作: https://daviddalpiaz.github.io/r4sl/k-nearest- neighbors.html#regression

I have been trying to follow a description of how to use "knn.reg" in 9.2 here: https://daviddalpiaz.github.io/r4sl/k-nearest-neighbors.html#regression

grid2=data.frame(x)
knn10 = FNN::knn.reg(train = x, test = grid2, y = y, k = 10)

我的预测值对我来说似乎是合理的,但是当我尝试在x〜y图上绘制一条线时,我没有得到我想要的.

My predicted values seem reasonable to me but when I try to plot a line with them on top of my x~y plot I don't get what I'm hoping for.

plot(x,y)
lines(grid2$x,knn10$pred)

我觉得我缺少明显的东西,非常感谢您能提供的任何帮助或建议,谢谢您的宝贵时间.

I feel like I'm missing something obvious and would really appreciate any help or advice you can offer, thank you for your time.

推荐答案

您只需要在绘制线条之前对x值进行排序.

You just need to sort the x values before plotting the lines.

plot(x,y)
ORD = order(grid2$x)
lines(grid2$x[ORD],knn10$pred[ORD])

这篇关于R中的Knn回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆