Search code examples
rrecommendation-enginemarkov

Build Markov Chains


I want to get the transition matrix for building a Markov chain model to build a recommender system. My data is in the form

            Date    StudentID   Subjectid
            201601   123        1
            201601   234        4
            201601   122        2
            201602   123        3
            201602   123        1
            201602   234        2
            201603   122        3

I want to predict the next three subject that the student is most likely to pick. I am finding it difficult to get this data in the form of transition matrix so that I can build a markov chain model.

I have tried the following code but I am not sure how the transition matrix will be generated. Please help!

              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)

Solution

  • To create a transition matrix, there is already a post regarding that. Your data should look something like this:

    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))
    

    then you can use this:

    install.packages('markovchain')
    library(markovchain)
    ...