-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path.Rhistory
224 lines (224 loc) · 11.3 KB
/
.Rhistory
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
test = 2
setwd("C:/Users/luc.bertin/Desktop/publicis") ; source("functions.R")
rm(list = ls())
cat("\014")
setwd("C:/Users/luc.bertin/Desktop/publicis") ; source("functions.R")
getwd()
setwd("C:/Users/luc.bertin/Desktop/publicis") ; source("functions.R")
getwd()
setwd("/publicis")
setwd("publicis")
setwd("publicis/")
setwd("/publicis/")
setwd("/Desktop/")
setwd("/Desktop")
usePackage("caret")
usePackage <- function(p) {
if (!is.element(p, installed.packages()[,1]))
install.packages(p, dependencies = TRUE)
require(p, character.only = TRUE)
}
importLibraries = function(){
usePackage("dplyr")
usePackage("MASS")
usePackage("ggplot2")
usePackage("grid")
usePackage("gridExtra")
usePackage("GGally")
usePackage("plyr")
usePackage("rlist")
usePackage("ggpubr")
usePackage("e1071")
usePackage("dataPreparation")
usePackage("ggcorrplot")
#dependencies
usePackage("recipes")
usePackage("caret")
usePackage("data.table")
usePackage("ROCR")
usePackage("randomForest")
usePackage("pROC")
}
usePackage("dplyr")
usePackage("MASS")
usePackage("ggplot2")
usePackage("grid")
usePackage("gridExtra")
usePackage("GGally")
usePackage("plyr")
usePackage("rlist")
usePackage("ggpubr")
usePackage("e1071")
usePackage("dataPreparation")
usePackage("ggcorrplot")
#dependencies
usePackage("recipes")
usePackage("caret")
usePackage("caret")
usePackage("data.table")
usePackage("ROCR")
usePackage("randomForest")
usePackage("pROC")
install.packages('devtools') #assuming it is not already installed
library(devtools)
install_github('andreacirilloac/updateR')
library(updateR)
updateR(admin_password = 'Admin user password')
install.packages('caret')
install.packages("caret", dependencies = c("Depends", "Suggests"))
library(caret)
install.packages('caret', repos='http://cran.rstudio.com/')
source('~/Desktop/publicis/functions.R')
knitr::opts_chunk$set(results = FALSE, echo = TRUE, warning = FALSE,
error = FALSE, message=FALSE, fig.align = "center", out.width = '100%')
getwd() #just to check
rm(list = ls()); cat("\014"); if(!is.null(dev.list())) dev.off()
source("functions.R")
#this could take some time depending on packages to be installed
importLibraries()
source('~/Desktop/publicis/functions.R')
# install.packages("randomForest")
library(randomForest)
library(randomForest)
usePackage("randomForest")
r <- read.csv(file = "data/OnlineNewsPopularity.csv", na.strings = ".", header = T)
r <- r[, !names(r) %in% c('url', 'timedelta')] #timedelta is useless
r <- prepare_data_parameter(df = r, parameter = "shares", MaxValueParameter = 1, step = 0.50)
r$percentile <- revalue(r$percentile, c('[1,1.4e+03]' = 0, '(1.4e+03,6.9e+05]'= 1))
r$shares <- NULL
train_test4 <- prepare_dataset(r = r, pourcentage_training_df = 0.85, target_variable = "percentile", verbose = F)
factors_dummies <- names(r[,grepl( "is", names(r))])
r <- read.csv(file = "data/OnlineNewsPopularity.csv", na.strings = ".", header = T)
r <- r[, !names(r) %in% c('url', 'timedelta')] #timedelta is useless
r <- prepare_data_parameter(df = r, parameter = "shares", MaxValueParameter = 1, step = 0.50)
r$percentile <- revalue(r$percentile, c('[1,1.4e+03]' = 0, '(1.4e+03,6.9e+05]'= 1))
r$shares <- NULL
train_test4 <- prepare_dataset(r = r, pourcentage_training_df = 0.85, target_variable = "percentile", verbose = F)
ranfomForestModel <- randomForest(target ~ ., data = cbind(as.data.frame(train_test4$X_train), train_test4$Y_train),
ntree = 500, na.action = na.omit)
#here na.omit is useless, there is no NA in the dataset, but still
summary(ranfomForestModel)
# Feature importance
ranfomForestModel$importance
varImpPlot(ranfomForestModel)
#prediction
predictions <- predict(ranfomForestModel, newdata = cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))
cm <- table(train_test4$Y_test$target, predictions)
cm
# # ROC Curve
score <- prediction(predictions, train_test4$Y_test$target)
optimal <- tuneRF(cbind(as.data.frame(train_test4$X_train)),train_test4$Y_train$target,
ntreeTry=100, stepFactor=1.5,improve=0.01, trace=TRUE, plot=TRUE, dobest=FALSE)
adult.rf.pr = ranfomForestModel
adult.rf.pr = predict(adult.rf,type="prob",newdata=train_test4$Y_test$target)[,2]
adult.rf.pr = predict(ranfomForestModel,type="prob",newdata=train_test4$Y_test$target)[,2]
?randomForest
#let's use the determined optimal number of mtry for each tree and create the model
adult.rf <-randomForest(target~.,data=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train),
mtry=10, ntree=200, keep.forest=TRUE, importance=TRUE, xtest=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train))
#let's use the determined optimal number of mtry for each tree and create the model
adult.rf <-randomForest(target~.,data=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train),
mtry=10, ntree=200, keep.forest=TRUE, importance=TRUE, xtest=train_test4$Y_train$target)
#let's use the determined optimal number of mtry for each tree and create the model
adult.rf <-randomForest(target~.,data=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train),
mtry=10, ntree=200, keep.forest=TRUE, importance=TRUE, test=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train))
#let's use the determined optimal number of mtry for each tree and create the model
adult.rf <-randomForest(target~.,data=cbind(as.data.frame(train_test4$X_train), train_test4$Y_train),
mtry=10, ntree=200, keep.forest=TRUE, importance=TRUE,
test=cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))
adult.rf.pr = predict(adult.rf,type="prob",newdata=cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))[,2]
adult.rf.pred = prediction(adult.rf.pr, train_test4$Y_test$target)
adult.rf.perf = performance(adult.rf.pred,"tpr","fpr")
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
abline(a=0,b=1,lwd=2,lty=2,col="gray")
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
abline(a=0,b=1,lwd=2,lty=2,col="gray")
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
abline(a=0,b=1,lwd=2,lty=2,col="gray",add=T)
plot.new(abline(a=0,b=1,lwd=2,lty=2,col="gray",add=Tx
))
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
plot.new(abline(a=0,b=1,lwd=2,lty=2,col="gray",add=Tx
))
plot(performance(score,'tpr','fpr'), col="#127CD4", lwd=3)
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
text(0.15,0.5,"Random Forest",col="#32CD32")
plot(adult.rf.perf,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
#ROC Curve
pr = predict(randomForestModel,type="prob",newdata=cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))[,2]
#ROC Curve
pr = predict(ranfomForestModel,type="prob",newdata=cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))[,2]
#ROC Curve
pr = predict(ranfomForestModel,type="prob",newdata=cbind(as.data.frame(train_test4$X_test), train_test4$Y_test))[,2]
pred = prediction(pr, train_test4$Y_test$target)
performancee = performance(pred,"tpr","fpr")
plot(performancee,main="ROC Curve for Random Forest",col="#32CD32",lwd=2)
vect =c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,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1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,4,4,4,
4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,
10,10,10,10,10,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,
14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
18,18,18,19,19,19,19,19,19,20,20,20,20,20,21,21,21,21,22,22,22,23,23,23,24,25,25,25,26,27,27,27,29,31,31,31,31,31,31,31,31,31,31,31,33,35,36,36,39,41,43,43,
45,45,45,46,48,52,53,54,72,77,80,83,91,106,131,137,148,181,186,213,221,227,228,236,237,244,272,289,304,339,366,375,441,481,605)
hist(vect)
hist(vect,breaks = 100)
summary(vect)
quantile(vect)
quantile(vect, 0.8)
quantile(vect, 0.9)
quantile(vect, 0.8)
setwd(dir = "/Users/lucbertin/Documents/3_ESILV Paris/5A/Selfish Mining")
library(ggplot2)
rfinal <- read.csv(file = "results_final15.txt", sep=',', na.strings = "NA", header = F)
library(ggplot2)
rfinal <- read.csv(file = "results_final15.txt", sep=',', na.strings = "NA", header = F)
nrow(rfinal)
colnames(rfinal) = c("alpha", "gamma", "nb_simulations", "currentTimestamp",
"totalValidatedBlocks", "honestsValidBlocks", "selfishValidBlocks",
"blockNumber", "ExpectedSMvalidatedBlocksIfHM",
"Sn0", "DifficultyChangedTo")
head(rfinal)
rfinal$id <- paste0(rfinal$alpha, '|', rfinal$gamma)
rfinal$blockSMperTime <- rfinal$selfishValidBlocks/rfinal$currentTimestamp
rfinal$blockSMperTimeifHM <- rfinal$ExpectedSMvalidatedBlocksIfHM/rfinal$currentTimestamp
length(unique(rfinal$id))
######### when number of id (alpha gamma) is low ############
## RATE OF TIME REWARD (Expected vs Real)
ggplot(rfinal, aes(x=blockNumber, group=as.factor(id)))+
geom_line(aes(y=blockSMperTime), color="red") +
geom_line(aes(y=blockSMperTimeifHM), linetype="dotted", color="blue") + theme_bw()+
facet_wrap(~id)
library(plyr)
df <- ddply(rfinal, .(id), summarize,
alpha = alpha,
gamma = gamma,
ProfitabilityTime = currentTimestamp,
selfishValidBlocks = selfishValidBlocks,
ExpectedSMvalidatedBlocksIfHM = ExpectedSMvalidatedBlocksIfHM,
profitable_dummy = cumsum(ifelse(selfishValidBlocks>ExpectedSMvalidatedBlocksIfHM, 1,0)))
timesOfprofitability <- df[df$profitable_dummy==1,]
timesOfprofitability[timesOfprofitability$alpha == "0.01",]
x = seq(0.0, 0.4999999, by=0.01)
y = (1-3*x)/(1-2*x)
theorical=data.frame(x,y)
# only take y > 0
theorical=theorical[theorical$y>=0, ]
ggplot(label="alpha")+
theme_bw()+geom_raster(data=timesOfprofitability[ timesOfprofitability$ProfitabilityTime <
quantile(timesOfprofitability$ProfitabilityTime,0.95), ],
aes(x=alpha, y=gamma, fill=ProfitabilityTime))+
labs(x=expression(~alpha : "Alpha (Relative Mining Power)"),
y=expression(~gamma : "Gamma (Proportion of HM mining on SM chain)"),
fill='Time (in min)\nby when SM\nmakes profits')+
labs(title="Alphas and Gammas for which Selfish Mining strategy becomes profitable",
subtitle="Red : Theorical | Shades of blue : simulation | nb Blocks Mined : 150,000")+
geom_line(data=theorical, aes(x=x,y=y), col='red', size=2)+
annotate('text', x=0.21, y=0.17, label="gamma==(1-3~alpha)/(1-2~alpha)", parse=T,size=7.2, col='red')