-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimateready.R
258 lines (136 loc) · 5.51 KB
/
climateready.R
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# **K-means**
## **Loading & Inspecting data**
### Set working directory
#setwd("...")
### Set the seed for reproducibility
set.seed(42) # Replace 123 with your desired seed value
### Read the csv
df <- read.csv("R_logistic_kmeans.csv", sep=";")
head(df, 3)
## **Pre-processing data**
### Function to convert TRUE/FALSE to 1/0
library(dplyr)
convert_to_binary <- function(x) {
as.numeric(x)
}
###Apply the function to all columns except the first one (assuming it's the index)
data_transformed <- df %>%
mutate_all(~ ifelse(. == "True", 1, ifelse(. == "False", 0, .)))
### Print the transformed data
head(data_transformed, 3)
names(data_transformed)
length(data_transformed)
nrow(data_transformed)
n = nrow(data_transformed)
n
### Define the response variables
# Specify the variable to be used as Y response
Y_response <- "cluster_kmeans"
# Extract the Y response
Y <- data_transformed[, Y_response]
# Extract the X response (all other variables)
X <- data_transformed[, setdiff(names(data_transformed), Y_response)]
### Identify variables to exclude from conversion to integer
exclude_variables <- c("Age", "meanTout")
### Convert all other variables to integer
X[, setdiff(names(X), exclude_variables)] <- lapply(X[, setdiff(names(X), exclude_variables)], as.integer)
### Verify the changes
str(X)
X_matrix <- as.matrix(X)
sum(Y)
head(cor(X_matrix),3)
### Columns to be removed (For preventing linear dependencies in the input matrix. We modify x so and remove similar columns.)
columns_to_remove <- c("is_31009", "dwelling_Other")
### Index of columns to keep
columns_to_keep <- !(colnames(X_matrix) %in% columns_to_remove)
### Remove columns
X_matrix <- X_matrix[, columns_to_keep]
### Scale predictors
X_matrix <- scale(X_matrix)
## **Analizing data**
### Penalized logistic regression
library(glmnet) # Install and load glmnet package
# Example using cross-validation to find the best lambda with cv = 5
cv_model <- cv.glmnet(X_matrix, Y, alpha = 1, family = "binomial", nfolds = 5, type.measure = "class")
plot(cv_model)
# Find the alpha and lambda with the minimum mean cross-validated error
best_lambda <- cv_model$lambda.min
best_lambda
best_model <- glmnet(X_matrix, Y, alpha = 1, lambda = best_lambda, family = "binomial")
coef(best_model, s = best_lambda)
### Selective inference
library(selectiveInference)
# extract coef for a given lambda; note the 1/n factor!
# (and here we DO include the intercept term)
beta = coef(best_model, x=X_matrix, y=Y, s = best_lambda/n)
# compute fixed lambda p-values and selection intervals
model = fixedLassoInf(X_matrix,Y,beta,best_lambda,family="binomial")
model
# **Hierarchical Clustering**
## **Loading & Inspecting data**
### Set working directory
#setwd("...")
### Set the seed for reproducibility
set.seed(42) # Replace 123 with your desired seed value
### Read the csv
df <- read.csv("R_logistic_hclust.csv", sep=";")
head(df, 3)
## **Pre-processing data**
### Function to convert TRUE/FALSE to 1/0
library(dplyr)
convert_to_binary <- function(x) {
as.numeric(x)
}
###Apply the function to all columns except the first one (assuming it's the index)
data_transformed <- df %>%
mutate_all(~ ifelse(. == "True", 1, ifelse(. == "False", 0, .)))
### Print the transformed data
head(data_transformed,3)
names(data_transformed)
length(data_transformed)
nrow(data_transformed)
n = nrow(data_transformed)
n
### Define the response variables
# Specify the variable to be used as Y response
Y_response <- "cluster_hierarchical"
# Extract the Y response
Y <- data_transformed[, Y_response]
# Extract the X response (all other variables)
X <- data_transformed[, setdiff(names(data_transformed), Y_response)]
### Identify variables to exclude from conversion to integer
exclude_variables <- c("Age", "meanTout")
### Convert all other variables to integer
X[, setdiff(names(X), exclude_variables)] <- lapply(X[, setdiff(names(X), exclude_variables)], as.integer)
### Verify the changes
str(X)
X_matrix <- as.matrix(X)
sum(Y)
head(cor(X_matrix),3)
### Columns to be removed (For preventing linear dependencies in the input matrix. We modify x so and remove similar columns)
columns_to_remove <- c("is_31009", "dwelling_Other")
### Index of columns to keep
columns_to_keep <- !(colnames(X_matrix) %in% columns_to_remove)
### Remove columns
X_matrix <- X_matrix[, columns_to_keep]
### Scale predictors
X_matrix <- scale(X_matrix)
## **Analizing data**
### Penalized logistic regression
library(glmnet) # Install and load glmnet package
# Example using cross-validation to find the best lambda with cv = 5
cv_model <- cv.glmnet(X_matrix, Y, alpha = 1, family = "binomial", nfolds = 5, type.measure = "class")
plot(cv_model)
# Find the alpha and lambda with the minimum mean cross-validated error
best_lambda <- cv_model$lambda.min
best_lambda
best_model <- glmnet(X_matrix, Y, alpha = 1, lambda = best_lambda, family = "binomial")
coef(best_model, s = best_lambda)
### Selective inference
library(selectiveInference)
# extract coef for a given lambda; note the 1/n factor!
# (and here we DO include the intercept term)
beta = coef(best_model, x=X_matrix, y=Y, s = best_lambda/n)
# compute fixed lambda p-values and selection intervals
model = fixedLassoInf(X_matrix,Y,beta,best_lambda,family="binomial")
model