-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path04_RFE_microarray.R
More file actions
193 lines (142 loc) · 6.64 KB
/
Copy path04_RFE_microarray.R
File metadata and controls
193 lines (142 loc) · 6.64 KB
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
# ===================================================================
# AI in Biotechnology & Bioinformatics Series
# ===================================================================
# -------------------------------------------------------------------
# Microarray Analysis – Part 4
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# Recursive Feature Selection using Random forest
# -------------------------------------------------------------------
# ===================================================================
#-----------------------------------------
#### STEP 1: Load and explore Dataset ####
#-----------------------------------------
# Install required packages for data analysis and modeling
install.packages("DataExplorer") # for exploratory data analysis
install.packages("caret") # for machine learning functions
install.packages("dplyr") # for data manipulation
# Load the libraries
library(DataExplorer)
library(caret)
library(dplyr)
# Import dataset
# already normalized microarray expression data
# Here's the link to access the dataset: https://github.com/AI-Biotechnology-Bioinformatics/Microarray_Series_R
data <- read.csv("gastric_cancer.csv")
# Check the number of rows and columns
dim(data)
# View the structure of the first few columns
head(str(data[1:6]))
# Perform exploratory data analysis
introduce(data) # Summary of dataset
plot_intro(data) # Visual summary of variables
plot_bar(data$labels) # Bar plot of sample labels (e.g., cancer vs normal)
plot_correlation(data) # Correlation between features (only numeric columns)
#-------------------------------
##### Step 2: Prepare data ####
#-------------------------------
# Select only gene expression features (excluding ID and labels)
x <- data %>%
select(-V1, -labels, -target) %>%
as.data.frame()
# Select the data labels
# convert it into numeric factor variable (e.g., 0 = normal, 1 = cancer)
y <- as.factor(data$labels,
levels = c("cancer", "normal"),
labels = c(1, 0))
class(y)
levels(y)
# Split the dataset into training (70%) and testing (30%) sets
index <- createDataPartition(y,
p = 0.7,
list = FALSE)
x_train <- x[index,] # train features
x_test <- x[-index,] # test features
y_train <- y[index] # train target
y_test <- y[-index] # test target
#--------------------------------------------
#### Step 4: Feature Selection with RFE ####
#--------------------------------------------
# Set up the RFE control with 10-fold cross-validation and Random Forest functions
ctrl <- rfeControl(functions = rfFuncs,
method = "cv",
number = 10,
verbose = TRUE)
# Apply RFE to select the most important features
# Sizes = number of top features to evaluate, set it accordingly
RFE_features <- rfe(x = x_train,
y = y_train,
sizes = c(1:5, 10, 30),
rfeControl = ctrl)
# View RFE results (e.g., which features performed best)
RFE_features
# Display the list of best performing features
predictors(RFE_features) #OR
RFE_features$optVariables
# Visualize the RFE results (accuracy vs number of features)
library(ggplot2)
ggplot(data = RFE_features,
metric = "Accuracy")
# Extract top 30 features with their importance scores
top_var <- data.frame(features = row.names(varImp(RFE_features))[1:10],
scores = varImp(RFE_features)[1:10, 1])
# Let’s save these selected features so you can use them later
write.csv(top_var, file = "RFE_top_features.csv", row.names = FALSE)
#---------------------------------------------------------------------
#### Step 5: Build Random Forest Model with RFE Selected Features ####
#---------------------------------------------------------------------
# subset train and test set with only RFE selected features
subset_train <- x_train[, imp_variables$features]
subset_test <- x_test[, imp_variables$features]
# Set up training control for cross-validation
rf_ctrl <- trainControl(method = "cv",
number = 10,
verboseIter = TRUE)
# Train the Random Forest model using the selected features
Rf_model <- train(x = subset_train,
y = y_train,
method = "rf",
trControl = rf_ctrl)
# Predict the target labels on the test set
pred <- predict(Rf_model, subset_test)
# Compare predictions with actual test labels
y_test # check the difference between predicted and actual target (observe model's miss classifications)
# Generate and print the confusion matrix (model evaluation)
conf <- confusionMatrix(pred, y_test)
print(conf)
# Extract the confusion matrix table
conf_table <- as.table(conf$table)
# Convert to data frame
conf_df <- as.data.frame(conf_table)
# Save to CSV
write.csv(conf_df, "Confusion_Matrix_RF.csv", row.names = FALSE)
# ---------------------------------------------------------------------
# 🎯 Practice Task: Recursive Feature Elimination with SVM
# ---------------------------------------------------------------------
# Bounce Question for You!
# Try running RFE using SVM instead of Random Forest.
# Here's a hint: SVM models are sensitive to the scale of the data.
# So, you'll need to **center and scale** the data before training.
# 📌 Tip:
# Models like Decision Trees and Random Forests **don't care** about feature scaling.
# But algorithms like **SVM** and **KNN** are sensitive to feature values.
# So always remember to scale your data when using these models.
# 👉 Try this:
# Use the 'svmFuncs' inside the 'rfeControl()' function instead of 'rfFuncs'.
# Also, use the 'preProcess = c("center", "scale")' argument to standardize your features.
# Example template to help you start:
ctrl_svm <- rfeControl(functions = svmFuncs,
method = "cv",
number = 10,
verbose = TRUE)
RFE_svm <- rfe(x = x_train,
y = y_train,
sizes = c(1:5, 10, 30),
rfeControl = ctrl_svm,
preProc = c("center", "scale"))
# Then check your results:
RFE_svm
predictors(RFE_svm)
# follow for more:
# github: https://github.com/AI-Biotechnology-Bioinformatics
# linkedin: https://www.linkedin.com/company/ai-and-biotechnology-bioinformatics/