~bendersteed/markov-chains-web-navigation

markov-chains-web-navigation/markov-chain-navigation.r -rw-r--r-- 6.5 KiB
b0516676 — Dimos Dimakakos Docs: update README 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
library(tidyverse)

## παίρνει τις διαδρομές και τις κάνει character vectors
parseData <- function(data_file, skip) {
    sapply(Filter(function(x) {nchar(x) > 2}, read_lines(data_file, skip = skip)), function(x) { strsplit(x, " ") })
}

topics <- c("frontpage", "news", "tech", "local", "opinion", "on-air", "misc", "weather", "msn-news",
            "health", "living", "business", "msn-sports", "sports", "summary", "bbs", "travel")

## εδώ για να προσθέτουμε τα resets σε κάθε διαδρομή, αυτή θα είναι ένα συν την τελευταία κατάσταση
addReset <- function(path, k, states) {
    RESET_ELEM <- "-1"
    if (k > 0) {
        c(as.character(array(RESET_ELEM, k)), path, as.character(RESET_ELEM))
    } else {
         c(path, as.character(RESET_ELEM))
    }
}

updateOrInit <- function(env,target,value) {
    if (is.null(env[[target]])) {
        env[[target]] <- new.env(hash = TRUE)
        env[[target]][[value]] <- 1
    } else {
        if (is.null(env[[target]][[value]])) {
            env[[target]][[value]] <-1
        } else {
            env[[target]][[value]] <- env[[target]][[value]] + 1
        }
    }
}

fitPaths <- function(paths, k, states) {
    FAKE_ELEM <- "0"
    result <- new.env(hash = TRUE)

    for (i in paths) {
        path <- addReset(i, k, states)
        len <- length(path)

        for(j in k:(len-1)) {
            value <- path[[j+1]]
            if (k == 0) {
                updateOrInit(result,FAKE_ELEM,value)
            } else {
                if (k == 1) {
                    target <- as.character(path[[j]])
                }
                else {
                    target <- paste(path[(j-k+1):j], collapse=",")
                }

                updateOrInit(result,target,value)
            }
        }
    }
    return(lapply(result, "as.list"))
}

## πιθανότητες μετάβασης
mlePaths <- function(fitted) {
    lapply(fitted, function(x) {
        sum <- Reduce("+", x)
        lapply(x, function(x) { x / sum})
    })
}

loglikelihood <- function(freqs) {
    unlisted_freqs <- unlist(freqs)
    probs <- unlist(mlePaths(freqs))

    sum(unlisted_freqs * log(probs))
}

## βαθμοί ελευθερίας
degreesOfFreedom <- function(states, k_null, k_test) {
    (states^k_test - states^k_null) * (states -1)
}

likelihoodRatio <- function(likelihood_null, likelihood_test) {
    -2 * (likelihood_null - likelihood_test)
}

aic <- function(likelihood_ratio, dof) {
    likelihood_ratio - 2 * dof
}

bic <- function(likelihood_ratio, dof, observation_count) {
    likelihood_ratio - dof * log(observation_count)
}



simulation <- function(input, k, states, topics = topics, skip = 7) {
    data <- parseData(input, skip)

    freqs <- sapply(0:k, function (x) { fitPaths(data, x, states) })
    zero_order <- tail(freqs[[1]][[1]], n = states) # remove reset element count for the calculation
    zero_order <- zero_order[as.character(sort(as.numeric(names(zero_order))))] # sort named list by numeric character
    observation_count <- sum(unlist(zero_order))
    freq_percentages <- tibble(ID = 1:states,
                               Topic = topics,
                               Frequency = sapply(zero_order, function(x) { x / observation_count }))

    loglikelihoods <- tibble(Order = 0:k,
                             Loglikelihood = sapply(0:k, function (x) { loglikelihood(freqs[[x+1]]) }))

    df <- tibble(Null = integer(),
                 Test = integer(),
                 LR = numeric(),
                 dofs = numeric(),
                 p_value = numeric(),
                 AIC = numeric(),
                 BIC = numeric())

    for (i in 0:(k-1)) {
        for (j in (i+1):k) {
            likelihood_ratio <- likelihoodRatio(loglikelihoods[[i+1, 2]],loglikelihoods[[j+1, 2]])
            dof <- degreesOfFreedom(states + 1, i, j)
            p <- 1 - pchisq(likelihood_ratio, dof)
            AIC <- aic(likelihood_ratio, dof)
            BIC <- bic(likelihood_ratio, dof, observation_count)
            
            df <- df %>% add_row(Null = i,
                                 Test = j,
                                 LR = likelihood_ratio,
                                 dofs = dof,
                                 p_value = p,
                                 AIC = AIC,
                                 BIC = BIC)
        }
    }
    return(list(frequencies = freq_percentages, loglikelihoods = loglikelihoods, results = df))
}

## plotting and data retrieval

freqCol <- function(freq_percentages) {
    ggplot(data = freq_percentages) +
        geom_col(mapping = aes(x = ID, y = Frequency, fill = Topic)) +
        labs(title = "Συχνότητες εμφάνισης θεματικών στο δείγμα")
}

loglikelihoodGraph <- function(loglikelihoods) {
    max <- loglikelihoods %>% filter(Loglikelihood == max(Loglikelihood))
    print(max)
    ggplot(data = loglikelihoods) +
        geom_path(mapping = aes(x = Order, y = Loglikelihood)) +
        geom_point(mapping = aes(x = Order, y = Loglikelihood),
                   shape = 15) +
        geom_point(mapping = aes(x = max$Order, y = max(Loglikelihood)),
                   colour = "red",
                   size = 3) +
        labs(title = "Λογαριθμο-πιθανοφάνειες για την ανάλογη τάξη Μαρκοβιανής αλυσίδας")
}

likelihoodRatioTable <- function(results) {
    results[c(1,2,3)]
}

aicGraph <- function(results, test_model) {
    aic <- results %>% filter(Test == test_model) %>% select(Null, AIC)
    min_null <- aic %>% filter(AIC == min(AIC))
    ggplot(data = aic) +
        geom_path(mapping = aes(x = Null, y = AIC)) +
        geom_point(mapping = aes(x = Null, y = AIC),
                   shape = 15) +
        geom_point(mapping = aes(x = min_null$Null, y = min(AIC)),
                   colour = "red",
                   size = 3) +
        labs(title = paste("AIC με εναλλακτική υπόθεση = ", test_model))
}

bicGraph <- function(results, test_model) {
    bic <- results %>% filter(Test == test_model) %>% select(Null, BIC)
    min_null <- bic %>% filter(BIC == min(BIC))
    ggplot(data = bic) +
        geom_path(mapping = aes(x = Null, y = BIC)) +
        geom_point(mapping = aes(x = Null, y = BIC),
                   shape = 15) +
        geom_point(mapping = aes(x = min_null$Null, y = min(BIC)),
                   colour = "red",
                   size = 3) +
        labs(title = paste("BIC με εναλλακτική υπόθεση = ", test_model))
}