在r产生na/nan/inf中的knn功能在外国功能呼叫中(arg 6)错误

发布于 2025-01-24 13:22:56 字数 1015 浏览 3 评论 0原文

我正在研究一个项目,我需要使用R构建KNN模型。教授提供了一篇文章,上面有分步说明(链接到Artist )和一些数据集可供选择(链接到我正在使用的数据)。我被困在第3步中(从培训数据中创建模型)。

这是我的代码:

data <- read.delim("data.txt", header = TRUE, sep = "\t", dec = ".") 
set.seed(2)
part <- sample(2, nrow(data), replace = TRUE, prob = c(0.65, 0.35))
training_data <- data[part==1,]
testing_data <- data[part==2,]
outcome <- training_data[,2]
model <- knn(train = training_data, test = testing_data, cl = outcome, k=10)

这是我收到的错误消息:

“错误消息”

我检查了一下,发现triagn_data,testing_data和结果看起来都是正确的,问题似乎仅与KNN模型有关。

I'm working on a project where I need to construct a knn model using R. The professor provided an article with step-by-step instructions (link to article) and some datasets to choose from (link to the data I'm using). I'm getting stuck on step 3 (creating the model from the training data).

Here's my code:

data <- read.delim("data.txt", header = TRUE, sep = "\t", dec = ".") 
set.seed(2)
part <- sample(2, nrow(data), replace = TRUE, prob = c(0.65, 0.35))
training_data <- data[part==1,]
testing_data <- data[part==2,]
outcome <- training_data[,2]
model <- knn(train = training_data, test = testing_data, cl = outcome, k=10)

Here's the error message I'm getting:

Error message

I checked and found that training_data, testing_data, and outcome all look correct, the issue seems to only be with the knn model.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑白记忆 2025-01-31 13:22:56

问题在于您的数据和您正在使用的knn功能;它无法处理角色或因素变量,

我们可以强迫这样做这样的工作:

library(tidyverse)

data <- data %>% 
            mutate(Seeded = as.numeric(as.factor(Seeded))-1) %>%
            mutate(Season = as.numeric(as.factor(Season)))

这通常是一个坏主意,因为季节不是自然而然的。一种更好的方法是将其视为一组假人。

请参阅此链接以获取示例:

r-从分类转换为knn

The issue is with your data and the knn function you are using; it can't handle characters or factor variable

We can force this to work doing something like this first:

library(tidyverse)

data <- data %>% 
            mutate(Seeded = as.numeric(as.factor(Seeded))-1) %>%
            mutate(Season = as.numeric(as.factor(Season)))

But this is a bad idea in general, since Season is not ordered naturally. A better approach would be to instead treat it as a set of dummies.

See this link for examples:

R - convert from categorical to numeric for KNN

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文