Forecast.svm不会预测新数据 [英] predict.svm does not predict new data

查看:60
本文介绍了Forecast.svm不会预测新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,在下面的简单示例中,我在使用predict()时遇到了问题:

unfortunately I have problems using predict() in the following simple example:

library(e1071)

x <- c(1:10)
y <- c(0,0,0,0,1,0,1,1,1,1)
test <- c(11:15)

mod <- svm(y ~ x, kernel = "linear", gamma = 1, cost = 2, type="C-classification")

predict(mod, newdata = test)

结果如下:

> predict(mod, newdata = test)
   1    2    3    4 <NA> <NA> <NA> <NA> <NA> <NA> 
   0    0    0    0    0    1    1    1    1    1 

有人可以解释为什么predict()只给出训练样本的拟合值(x,y),而不关心测试数据吗?

Can anybody explain why predict() only gives the fitted values of the training sample (x,y) and does not care about the test-data?

非常感谢您的帮助!

理查德

推荐答案

它看起来像是因为您误用了svm()的公式接口.通常,提供一个数据框或类似对象,在其中搜索公式中的变量.即使不这样做,通常也没关系,即使这不是最佳实践,但是当您要进行预测时, not 将变量放入数据框中会使您陷入混乱.它返回训练数据的原因是因为您没有为newdata提供包含名为x的组件的对象.因此,它找不到新数据x,因此返回拟合值.对于我所知道的大多数R predict方法,这是很常见的.

It looks like this is because you misuse the formula interface to svm(). Normally, one supplies a data frame or similar object within which the variables in the formula are searched for. It usually doesn't matter if you don't do this, even if it is not best practice, but when you want to predict, not putting variables in a data frame gets you in a right mess. The reason it returns the training data is because you don't provide newdata an object with a component named x in it. Hence it can't find the new data x so returns the fitted values. This is common for most R predict methods I know.

然后的解决方案是:i)将训练数据放在数据框中,并将svm作为data参数传递,并且ii)提供一个包含x(来自test)的新数据框到predict().例如:

The solution then is to i) put your training data in a data frame and pass svm this as the data argument, and ii) supply a new data frame containing x (from test) to predict(). E.g.:

> DF <- data.frame(x = x, y = y)
> mod <- svm(y ~ x, data = DF, kernel = "linear", gamma = 1, cost = 2,
+ type="C-classification")
> predict(mod, newdata = data.frame(x = test))
1 2 3 4 5 
1 1 1 1 1 
Levels: 0 1

这篇关于Forecast.svm不会预测新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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