Home Articles

带滚动窗口的SVM

Asked
Viewed 533 times
1

我有一个代码可以预测未来回报的变化 .

library(quantmod)
library(PerformanceAnalytics)
library(forecast)
library(e1071)
library(caret)
library(kernlab)
library(dplyr)
library(roll)
# get data yahoo finance
getSymbols("^GSPC", from = "1990-01-01", to = "2017-12-01") 
# take logreturns
rnull <- CalculateReturns(prices = GSPC$GSPC.Adjusted ,method ="log")
# lags 1, 2, 3, 4, 5 as features
feat <- merge(na.trim(lag(rnull,1)),na.trim(lag(rnull,2)),na.trim(lag(rnull,3)),na.trim(lag(rnull,4)),na.trim(lag(rnull,5)),all=FALSE)
# create dataset. 6th column is actural. Previous is lagged
dataset <- merge(feat,rnull,all=FALSE)
# set columns' names
colnames(dataset) = c("lag.1", "lag.2", "lag.3","lag.4","lag.5","TARGET")
# get signs and make a data.frame
x <- sign(dataset)%>%as.data.frame
# exclude 0 sign and assume that these values are positive
x[x==0] <- 1
# for svm purposes we need to set dependent variable as factor and make levels to interpretation
x$TARGET <- as.factor(as.character(x$TARGET))
levels(x$TARGET) <- list(positive = "1", negative = "-1")
# divide sample to training and test subsamples
trainindex <- x[1:5792,]
testindex <- x[5792:7030,]
# run svm
svmFit <- ksvm(TARGET~.,data=trainindex,type="C-svc",kernel= "rbfdot")
# prediction
predsvm <- predict(svmFit, newdata=testindex)
# results
confusionMatrix(predsvm, testindex$TARGET)

接下来我要做的是为我的模型添加一个滚动窗口(1步预测) . 但是,rollapply的基本方法不适用于dataframe . 对于时间序列的一步预测的Commom方法对于e1071包中使用的data.frame也无效 . 我写了以下函数:

svm_next_day_prediction <- function(x){
      svmFit <- svm(TARGET~., data=x)
      prediction <- predict(object = svmFit, newdata = tail(x,1) )
      return(prediction) 
    }  


    apl = rollapplyr(data = x, width = 180, FUN = svm_next_day_prediction, by.column = TRUE)

但收到错误,因为rollapply不理解data.frames:

terms.formula(formula,data = data)中的错误:' . '在公式中没有'数据'参数

你能解释一下如何用数据框应用svm分类模型的滚动窗口吗?

2 Answers

  • 0

    几点

    • rollapply 适用于可以强制转换为矩阵的数据帧,因此请确保您的输入完全是数字 - 而不是数字和因子的混合 . 例如,这可以使用内置数据框 BOD ,它有两个数字列 . 注意,传递给 predx 是一个矩阵 .
    pred <- function(x) predict(svm(demand ~ Time, x))
    rollapplyr(BOD, 3, FUN = pred, by.column = FALSE)
    

    ##              1        2        3
    ## [1,]  8.868888 10.86889 17.25474
    ## [2,] 11.661666 17.24870 16.00000
    ## [3,] 18.328435 16.18583 15.78583
    ## [4,] 16.230474 15.83247 19.56886
    
    • 我无法重现你得到的错误 . 我得到了一个不同的错误 .

    • 问题中的代码有 by.column = TRUE (无论如何都是默认值)但是它的结果是只将一个向量传递给函数,这不是你想要的 . 你想 by.column = FALSE .

    试试这个:

    x0 <- data.matrix(x)
    rollapplyr(data = x0, width = 180, FUN = svm_next_day_prediction, by.column = FALSE)
    
  • 0

    您可以创建包含各个数据框的列表,然后应用您的功能 . 我将x重命名为df以避免混淆:

    df=x
    rowwindow=179
    dfList=lapply(1:(nrow(df)-rowwindow),function(x) df[x:(rowwindow+x),])
    result=sapply(dfList,svm_next_day_prediction)
    

Related