R 建立马尔可夫链

R 建立马尔可夫链,r,recommendation-engine,markov,R,Recommendation Engine,Markov,我想得到建立马尔可夫链模型以建立推荐系统的转移矩阵。我的数据在表格中 Date StudentID Subjectid 201601 123 1 201601 234 4 201601 122 2 201602 123 3 201602 123 1

我想得到建立马尔可夫链模型以建立推荐系统的转移矩阵。我的数据在表格中

            Date    StudentID   Subjectid
            201601   123        1
            201601   234        4
            201601   122        2
            201602   123        3
            201602   123        1
            201602   234        2
            201603   122        3
我想预测学生最有可能选择的下三门课程。 我发现很难以转移矩阵的形式获得这些数据,以便建立马尔可夫链模型

我尝试了以下代码,但我不确定转换矩阵将如何生成。请帮忙

              rf <- (data$Subjectid)
              n <- (length(train$Subjectid))
              trf <- table(data.frame(data$Subjectid[1:(n-
               2)],data$Subjectid[1:(n-1)],data$Subjectid[2:n]))
                trf/rowSums(trf)

为了创建一个过渡矩阵,已经有了一个关于这一点的解决方案。您的数据应该如下所示:

df1 <- as.data.frame.matrix(table(data[,c("StudentID","Subjectid")]))
#function
trans.matrix <- function(X, prob=T)
{
    tt <- table( c(X[,-ncol(X)]), c(X[,-1]) )
    if(prob) tt <- tt / rowSums(tt)
    tt
}
transition_df <- trans.matrix(as.matrix(df1))

可能有更奇特的解决方案,但如果我正确理解了您要查找的内容,那么这将返回转换计数矩阵

df = read.table(text="Date    StudentID   Subjectid
201601   123        1
201601   234        4
201601   122        2
201602   123        3
201602   123        1
201602   234        2
201603   122        3",header=T)

library(dplyr)
library(tidyr)

df1 = do.call(rbind,lapply(split(df,df$StudentID), function(x) {x$prev_id = c(NA,x$Subjectid[1:(nrow(x)-1)]); return(x)} ))

df1$prev_id = factor(df1$prev_id,levels=unique(sort(c(df1$prev_id,df1$Subjectid))))
df1$Subjectid = factor(df1$Subjectid,levels=unique(sort(c(df1$prev_id,df1$Subjectid))))

df1 = df1[!is.na(df1$prev_id),] %>% group_by(Subjectid,prev_id) %>% 
  tally %>% spread(Subjectid,n,drop=FALSE,fill=0) %>% as.data.frame
输出:

  prev_id 1 2 3 4
1       1 0 0 1 0
2       2 0 0 1 0
3       3 1 0 0 0
4       4 0 1 0 0

您是否正在尝试实施此文件?
  prev_id 1 2 3 4
1       1 0 0 1 0
2       2 0 0 1 0
3       3 1 0 0 0
4       4 0 1 0 0