Group Members:
Name: Student ID

Rafia Hossain: 22097853

Huangfu Yiying:22084141

Wang Shengnan:22104025

Duan Yangqi:22098783

Zhang Xuan:22091244



Contents:

1 Introduction

2 Objectives

3 Data cleaning

3.1 Dataset details

3.2 Data cleaning process

4 Classification problem

4.1 Define problem & question

4.2 Modeling

4.3 Evaluation of model

4.4 Visualisation

4.5 Final Model Choice

4.6 Discussion of Output

5 Regression problem

5.1 Define problem & question

5.2 Modeling

5.3 Evaluation of model

5.4 Visualisation

5.5 Final Model Choice

5.6 Discussion of Output

6 Evaluation

7 Conclusion


1.Introduction

Cervical cancer In 2020, an estimated 604 000 women were diagnosed with cervical cancer worldwide and about 342 000 women died from the disease. The main cause of cervical cancer is persistent infection with high-risk types of human papillomavirus (HPV), an extremely common family of viruses that are transmitted through sexual contact. Vaccines exist that protect against high-risk HPV types, and screening programmes can detect signs of disease at an early stage, allowing for effective treatment and management of the condition. This means that cervical cancer should be one of the most preventable and treatable forms of cancer. ​

Hospital Universitario de Caracas The dataset was collected at ‘Hospital Universitario de Caracas’ in Caracas, Venezuela. The dataset comprises demographic information, habits, and historic medical records of 858 patients. Several patients decided not to answer some of the questions because of privacy concerns (missing values). This dataset focuses on the prediction of indicators/diagnosis of cervical cancer. The features cover demographic information, habits, and historic medical records.​


2.Objectives

I. To predict cervical cancer risk … (Classification)

Research on cervical cancer involves classifying patient samples using clinical data, biomarkers, and other features to predict their risk or condition of having cervical cancer. This can assist doctors in identifying high-risk patients and implementing preventive measures.

II. To predict the number of pregnancies in cervical-cancer-positive patients (Regression)

To predict the Number of Pregnancies of cervical-cancer-positive patients. We aim for performance metrics above the R-square threshold, 0.75, and below the Mean Square Error threshold, 1, to achieve accurate predictions and gather valuable insights in this specific healthcare domain.

III. To evaluate the model’s performances (Evaluation)

Using accuracy score, ROC score, F1 score, and recall score, among other performance metrics, we assessed the classification model’s performance across different aspects. For the regression model we considered Mean Square Error, Root Mean Square Error, Mean Absolute Error and R-square values. Considering the model’s performance on various metrics, we selected the one that performed the best for the given task.


3. Data Cleaning

3.1 Dataset Details

Hospital This dataset was collected at ‘Hospital Universitario de Caracas’ in Caracas, Venezuela. The dataset comprises demographic information, habits, and historic medical records of 858 patients. Several patients decided not to answer some of the questions because of privacy concerns (missing values). This dataset focuses on the prediction of indicators/diagnosis of cervical cancer. The features cover demographic information, habits, and historic medical records.

3.2 Data Cleaning Process

Read file from the csv

options(repos = c(CRAN = "https://cran.rstudio.com/"))
# Import data.
data <- read.csv("D:/ivy/7004R/kag_risk_factors_cervical_cancer.csv")
# Set the maximum number of columns displayed for a data frame or table.
options(max.print = 40)
# Display the first 20 rows of the data frame 'data'
head(data, 20)
##   Age Number.of.sexual.partners First.sexual.intercourse Num.of.pregnancies
## 1  18                       4.0                     15.0                1.0
##   Smokes Smokes..years. Smokes..packs.year. Hormonal.Contraceptives
## 1    0.0            0.0                 0.0                     0.0
##   Hormonal.Contraceptives..years. IUD IUD..years. STDs STDs..number.
## 1                             0.0 0.0         0.0  0.0           0.0
##   STDs.condylomatosis STDs.cervical.condylomatosis STDs.vaginal.condylomatosis
## 1                 0.0                          0.0                         0.0
##   STDs.vulvo.perineal.condylomatosis STDs.syphilis
## 1                                0.0           0.0
##   STDs.pelvic.inflammatory.disease STDs.genital.herpes
## 1                              0.0                 0.0
##   STDs.molluscum.contagiosum STDs.AIDS STDs.HIV STDs.Hepatitis.B STDs.HPV
## 1                        0.0       0.0      0.0              0.0      0.0
##   STDs..Number.of.diagnosis STDs..Time.since.first.diagnosis
## 1                         0                                ?
##   STDs..Time.since.last.diagnosis Dx.Cancer Dx.CIN Dx.HPV Dx Hinselmann
## 1                               ?         0      0      0  0          0
##   Schiller Citology Biopsy
## 1        0        0      0
##  [ reached 'max' / getOption("max.print") -- omitted 19 rows ]
# Checking the dimensions
dim(data)
## [1] 858  36
# Replacing '?' with Numpy NaN values.
data[data == "?"] <- NA
# Check the value again.
head(data, 20)
##   Age Number.of.sexual.partners First.sexual.intercourse Num.of.pregnancies
## 1  18                       4.0                     15.0                1.0
##   Smokes Smokes..years. Smokes..packs.year. Hormonal.Contraceptives
## 1    0.0            0.0                 0.0                     0.0
##   Hormonal.Contraceptives..years. IUD IUD..years. STDs STDs..number.
## 1                             0.0 0.0         0.0  0.0           0.0
##   STDs.condylomatosis STDs.cervical.condylomatosis STDs.vaginal.condylomatosis
## 1                 0.0                          0.0                         0.0
##   STDs.vulvo.perineal.condylomatosis STDs.syphilis
## 1                                0.0           0.0
##   STDs.pelvic.inflammatory.disease STDs.genital.herpes
## 1                              0.0                 0.0
##   STDs.molluscum.contagiosum STDs.AIDS STDs.HIV STDs.Hepatitis.B STDs.HPV
## 1                        0.0       0.0      0.0              0.0      0.0
##   STDs..Number.of.diagnosis STDs..Time.since.first.diagnosis
## 1                         0                             <NA>
##   STDs..Time.since.last.diagnosis Dx.Cancer Dx.CIN Dx.HPV Dx Hinselmann
## 1                            <NA>         0      0      0  0          0
##   Schiller Citology Biopsy
## 1        0        0      0
##  [ reached 'max' / getOption("max.print") -- omitted 19 rows ]
# Download needed packages and Checking the percentage of the missing values.
suppressWarnings({install.packages("ggplot2")
install.packages("dplyr")
install.packages("tidyr")
install.packages("magrittr")
install.packages("rpart") 
install.packages("caret")
library(ggplot2)
library(dplyr)
library(tidyr)
library(magrittr)
library(rpart)
library(caret)
})
## 程序包'ggplot2'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'dplyr'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'tidyr'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'magrittr'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'rpart'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'caret'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 
## 载入程辑包:'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## 
## 载入程辑包:'magrittr'
## The following object is masked from 'package:tidyr':
## 
##     extract
## 载入需要的程辑包:lattice
# Calculate the percentage of missing values in each column

missing_percentage <- data %>%
summarise(across(everything(), ~mean(is.na(.)) * 100)) %>%
pivot_longer(everything(), names_to = "Column", values_to = "Missing_Percentage") %>%
arrange(desc(Missing_Percentage))

# Create a horizontal bar plot
ggplot(missing_percentage, aes(x = reorder(Column, -Missing_Percentage), y = Missing_Percentage)) +
geom_bar(stat = "identity", fill = "skyblue") +
coord_flip() +
labs(x = "Columns", y = "Missing Percentage (%)", title = "Missing Values Percentage by Column")

We can see that the features ‘STD_Time_since_first_diagnosis’,‘STDs_Time_since_last_diagnosis’ are having more than 80 % null values. So we are dropping it off and also the features ‘Smokes’ and ‘First_sexual_intercourse’ are having very little amount of null values and hence we would be removing those particular missing records of those 2 columns.

# Drop 'STD_Time_since_first_diagnosis' and 'STDs_Time_since_last_diagnosis' Columns
data <- data %>%
  select(-c('STDs..Time.since.first.diagnosis', 'STDs..Time.since.last.diagnosis'))

# Delete rows where the 'Smokes' or 'First_sexual_intercourse' columns contain missing values.
data <- data %>%
  filter(!is.na(Smokes..years.) & !is.na(First.sexual.intercourse))
# We can see that the columns names contains spaces and colons. So renaming the columns for convenience
# Modify the columns name
colnames(data) <- c('Age', 'No_of_sex_partner', 'First_sexual_intercourse','No_pregnancies', 'Smokes', 'Smokes_yrs', 'Smokes_packs_yr', 'Hormonal_Contraceptives','Hormonal_Contraceptives_years', 'IUD', 'IUD_years', 'STDs', 'STDs_number', 'STDs_condylomatosis','STDs_cervical_condylomatosis', 'STDs_vaginal_condylomatosis', 'STDs_vulvo_perineal_condylomatosis','STDs_syphilis', 'STDs_pelvic_inflammatory_disease', 'STDs_genital_herpes', 'STDs_molluscum_contagiosum','STDs_AIDS', 'STDs_HIV', 'STDs_Hepatitis_B', 'STDs_HPV', 'STDs_No_of_diagnosis', 'Dx_Cancer', 'Dx_CIN', 'Dx_HPV', 'Dx', 'Hinselmann', 'Schiller', 'Citology', 'Biopsy')
#Check the value again
head(data, 20)
##   Age No_of_sex_partner First_sexual_intercourse No_pregnancies Smokes
## 1  18               4.0                     15.0            1.0    0.0
##   Smokes_yrs Smokes_packs_yr Hormonal_Contraceptives
## 1        0.0             0.0                     0.0
##   Hormonal_Contraceptives_years IUD IUD_years STDs STDs_number
## 1                           0.0 0.0       0.0  0.0         0.0
##   STDs_condylomatosis STDs_cervical_condylomatosis STDs_vaginal_condylomatosis
## 1                 0.0                          0.0                         0.0
##   STDs_vulvo_perineal_condylomatosis STDs_syphilis
## 1                                0.0           0.0
##   STDs_pelvic_inflammatory_disease STDs_genital_herpes
## 1                              0.0                 0.0
##   STDs_molluscum_contagiosum STDs_AIDS STDs_HIV STDs_Hepatitis_B STDs_HPV
## 1                        0.0       0.0      0.0              0.0      0.0
##   STDs_No_of_diagnosis Dx_Cancer Dx_CIN Dx_HPV Dx Hinselmann Schiller Citology
## 1                    0         0      0      0  0          0        0        0
##   Biopsy
## 1      0
##  [ reached 'max' / getOption("max.print") -- omitted 19 rows ]
# Check the dimension
dim(data)
## [1] 838  34

Check the empty rate again

# Calculate the percentage of missing values in each column
missing_percentage <- data %>%
summarise(across(everything(), ~mean(is.na(.)) * 100)) %>%
pivot_longer(everything(), names_to = "Column", values_to = "Missing_Percentage") %>%
arrange(desc(Missing_Percentage))

# Create a horizontal bar plot
ggplot(missing_percentage, aes(x = reorder(Column, -Missing_Percentage), y = Missing_Percentage)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  geom_text(aes(label = sprintf("%.2f%%", Missing_Percentage)), hjust = -0.2, size = 3) +  # Add number label
  coord_flip() +
  labs(x = "Columns", y = "Missing Percentage (%)", title = "Missing Values Percentage by Column")

# Checking the datatypes
# View the structure and summary information of the dataframe.
str(data)
## 'data.frame':    838 obs. of  34 variables:
##  $ Age                               : int  18 15 52 46 42 51 26 45 44 44 ...
##  $ No_of_sex_partner                 : chr  "4.0" "1.0" "5.0" "3.0" ...
##  $ First_sexual_intercourse          : chr  "15.0" "14.0" "16.0" "21.0" ...
##  $ No_pregnancies                    : chr  "1.0" "1.0" "4.0" "4.0" ...
##  $ Smokes                            : chr  "0.0" "0.0" "1.0" "0.0" ...
##  $ Smokes_yrs                        : chr  "0.0" "0.0" "37.0" "0.0" ...
##  $ Smokes_packs_yr                   : chr  "0.0" "0.0" "37.0" "0.0" ...
##  $ Hormonal_Contraceptives           : chr  "0.0" "0.0" "1.0" "1.0" ...
##  $ Hormonal_Contraceptives_years     : chr  "0.0" "0.0" "3.0" "15.0" ...
##  $ IUD                               : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ IUD_years                         : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs                              : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_number                       : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_condylomatosis               : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_cervical_condylomatosis      : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_vaginal_condylomatosis       : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_vulvo_perineal_condylomatosis: chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_syphilis                     : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_pelvic_inflammatory_disease  : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_genital_herpes               : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_molluscum_contagiosum        : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_AIDS                         : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_HIV                          : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_Hepatitis_B                  : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_HPV                          : chr  "0.0" "0.0" "0.0" "0.0" ...
##  $ STDs_No_of_diagnosis              : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Dx_Cancer                         : int  0 0 1 0 0 0 0 1 0 0 ...
##  $ Dx_CIN                            : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Dx_HPV                            : int  0 0 1 0 0 0 0 1 0 0 ...
##  $ Dx                                : int  0 0 0 0 0 0 0 1 0 0 ...
##  $ Hinselmann                        : int  0 0 0 0 0 1 0 0 0 0 ...
##  $ Schiller                          : int  0 0 0 0 0 1 0 0 0 0 ...
##  $ Citology                          : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Biopsy                            : int  0 0 0 0 0 1 0 0 0 0 ...
summary(data)
##       Age        No_of_sex_partner  First_sexual_intercourse No_pregnancies    
##  Min.   :13.00   Length:838         Length:838               Length:838        
##     Smokes           Smokes_yrs        Smokes_packs_yr   
##  Length:838         Length:838         Length:838        
##  Hormonal_Contraceptives Hormonal_Contraceptives_years     IUD           
##  Length:838              Length:838                    Length:838        
##   IUD_years             STDs           STDs_number        STDs_condylomatosis
##  Length:838         Length:838         Length:838         Length:838         
##  STDs_cervical_condylomatosis STDs_vaginal_condylomatosis
##  Length:838                   Length:838                 
##  STDs_vulvo_perineal_condylomatosis STDs_syphilis     
##  Length:838                         Length:838        
##  STDs_pelvic_inflammatory_disease STDs_genital_herpes
##  Length:838                       Length:838         
##  STDs_molluscum_contagiosum  STDs_AIDS           STDs_HIV        
##  Length:838                 Length:838         Length:838        
##  STDs_Hepatitis_B     STDs_HPV         STDs_No_of_diagnosis   Dx_Cancer      
##  Length:838         Length:838         Min.   :0.00000      Min.   :0.00000  
##      Dx_CIN            Dx_HPV              Dx            Hinselmann     
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##     Schiller          Citology           Biopsy       
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
## [到达getOption("max.print") -- 略过5行]]

Partioning the features manually into categorical and numerical. We are doing it manually it because there are a few columns like ‘No_of_sex_partner’ , ‘First_Sexual_intercourse’ , ‘No_pregnancies’ are actually of object categorical type but which should be of numerical type in general.

# Obtain columns name
x_features <- colnames(data)

# Remove columns 'Biopsy'
x_features <- setdiff(x_features, 'Biopsy')
# Create a list containing the names of categorical variable columns.
x_features_categorical <- c('Smokes', 'Hormonal_Contraceptives', 'IUD', 'STDs', 'STDs_condylomatosis', 
'STDs_cervical_condylomatosis','STDs_vaginal_condylomatosis','STDs_vulvo_perineal_condylomatosis','STDs_syphilis', 'STDs_pelvic_inflammatory_disease','STDs_genital_herpes','STDs_molluscum_contagiosum','STDs_AIDS', 'STDs_HIV', 'STDs_Hepatitis_B', 'STDs_HPV', 'Dx_Cancer', 'Dx_CIN', 'Dx_HPV', 'Dx')
# Create a list of numerical variable column names.
x_features_numerical <- setdiff(x_features, x_features_categorical)

Missing Values Imputation

As the dataset is a sensitive and medical one, we are not going to use the method of imputation using Mean or Median or Mode. Instead here we have used Machine Learning Models to fill the missing values.

The steps followed are :

1.Remove the column that needs to be imputed from the independent columns list.

2.For everyother independent column in the list (other than the column we are going to impute), fill the null values with mode/median depending on their datatype.

3.The concept in ML based imputation is that, we will choose the column that needs to be imputed as our ‘Y’ and remaining all as ‘X’ (basically in Step 2, we are imputing X columns so that X columns wont have missing values while training the model)

4.So now, Y alone will be having null values that needs to be imputed.

5.Test data will be those records that contains missing values of Y where as training records will be those records that have filled values of Y.

6.So we build a ML model and train it with filled values and predict the missing values of Y.

7.For Numerical columns we choosed DecisionTreeRegressor and for Categorical columns we built DecisionTreeClassifier models.

Missing Value Imputation of IUD

# create df_iud dataframe and fill empty values.
df_iud <- data

# Impute missing values for categorical feature columns.
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_iud[[i]]), decreasing = TRUE))[1]
  df_iud[[i]][is.na(df_iud[[i]])] <- mode_value
}

# Impute missing values for numerical feature columns.
for (i in x_features_numerical) {
  median_value <- median(df_iud[[i]], na.rm = TRUE)
  df_iud[[i]][is.na(df_iud[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
# Convert the feature columns to floating-point data types.
df_iud[] <- lapply(df_iud, as.numeric)

# Replace 0 and 1 with 'no' and 'yes' in categorical feature columns.
df_iud[x_features_categorical] <- lapply(df_iud[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

# One-hot encode categorical feature columns.
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.factor(x)) as.character(x) else x))
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.character(x)) factor(x) else x))
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.factor(x)) as.character(x) else x))
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.character(x)) factor(x) else x))
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.factor(x)) as.numeric(x) else x))
df_iud <- as.data.frame(lapply(df_iud, function(x) if(is.character(x)) as.numeric(x) else x))

# Select training and testing datasets.
train_iud <- subset(df_iud, !is.na(IUD))
test_iud <- subset(df_iud, is.na(IUD))

# Create training and testing sets for features and labels.
train_iud_x <- train_iud[, !names(train_iud) %in% "IUD"]
train_iud_y <- train_iud$IUD

test_iud_x <- test_iud[, !names(test_iud) %in% "IUD"]
test_iud_y <- test_iud$IUD

# Create a decision tree model using the rpart() function from the rpart package.
suppressWarnings({
library(rpart)
})
# Build a decision tree model.
iud_model <- rpart(IUD ~ ., data = train_iud, method = "class")

# Predict the 'IUD' column for the test set.
test_iud$IUD <- predict(iud_model, newdata = test_iud_x, type = "class")

# Merge the data.
iud_complete <- rbind(train_iud, test_iud)

# Create a new dataframe and fill the 'IUD' column.
df_impute <- data
df_impute$IUD <- iud_complete$IUD[order(rownames(df_impute))]
table(df_impute$IUD)
## 
##   1   2 
## 757  81

Missing Value Imputation for IUD_years Here we can impute the missing values of IUD years considering the following reasons For all the zero values of IUD_years, the value of IUD is zero. For the zero values of IUD , the value of IUD_years is zero. The predicted value of IUD is completely zero and hence we can consider that the predicted value of IUD years will also be zero.

# Remove an element from a list           
x_features_numerical <- x_features_numerical[!(x_features_numerical %in% c("IUD_years"))]
# Fill missing values in a column of a dataframe
df_impute$IUD_years[is.na(df_impute$IUD_years)] <- 0

Missing Value Imputation for Hormonal_Contraceptives

df_hor <- df_impute[, !colnames(df_impute) %in% "Biopsy"]


x_features_categorical <- setdiff(x_features_categorical, 'Hormonal_Contraceptives')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_hor[[i]]), decreasing = TRUE))[1]
  df_hor[[i]][is.na(df_hor[[i]])] <- mode_value
}


for (i in x_features_numerical) {
  median_value <- median(df_hor[[i]], na.rm = TRUE)
  df_hor[[i]][is.na(df_hor[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_hor[] <- lapply(df_hor, as.numeric)

numeric_columns <- colnames(df_hor)[sapply(df_hor, is.numeric)]

df_hor[x_features_categorical] <- lapply(df_hor[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_hor <- subset(df_hor, !is.na(Hormonal_Contraceptives))
test_hor <- subset(df_hor, is.na(Hormonal_Contraceptives))

train_hor_x <- subset(train_hor, select = -c(Hormonal_Contraceptives))
train_hor_y <- train_hor$Hormonal_Contraceptives

test_hor_x <- subset(test_hor, select = -c(Hormonal_Contraceptives))
test_hor_y <- test_hor$Hormonal_Contraceptives

suppressWarnings({library(rpart)})

hor_model <- rpart(Hormonal_Contraceptives ~ ., data = train_hor, method = "class")

test_hor$Hormonal_Contraceptives <- predict(hor_model, newdata = test_hor_x, type = "class")

hor_complete <- rbind(train_hor, test_hor)

df_impute$Hormonal_Contraceptives <- hor_complete$Hormonal_Contraceptives[order(rownames(df_impute))]
table(df_impute$Hormonal_Contraceptives)
## 
##   0   1 
## 282 556

Missing Value Imputation for Hormonal_Contraceptives_Years

df_hor_y <- df_impute[, !(names(df_impute) %in% c('Biopsy'))]


x_features_numerical <- x_features_numerical[!(x_features_numerical %in% c('Hormonal_Contraceptives_years'))]

# Fill missing values in categorical features using the mode.
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_hor_y[[i]]), decreasing = TRUE))[1]
  df_hor_y[[i]][is.na(df_hor_y[[i]])] <- mode_value
}

# Fill missing values in numerical features using the median.
for (i in x_features_numerical) {
  df_hor_y[[i]][is.na(df_hor_y[[i]])] <- median(df_hor_y[[i]], na.rm = TRUE)
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
# Convert the data frame to a floating-point type.
df_hor_y[] <- lapply(df_hor_y, as.numeric)

df_hor_y[x_features_categorical] <- lapply(df_hor_y[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
  return(x)
})

train_hor_yrs <- df_hor_y[!is.na(df_hor_y$Hormonal_Contraceptives_years), ]
test_hor_yrs <- df_hor_y[is.na(df_hor_y$Hormonal_Contraceptives_years), ]
train_hor_yrs_x <- train_hor_yrs[, !(names(train_hor_yrs) %in% c('Hormonal_Contraceptives_years'))]
train_hor_yrs_y <- train_hor_yrs$Hormonal_Contraceptives_years
test_hor_yrs_x <- test_hor_yrs[, !(names(test_hor_yrs) %in% c('Hormonal_Contraceptives_years'))]
test_hor_yrs_y <- test_hor_yrs$Hormonal_Contraceptives_years

dt <- rpart(train_hor_yrs_y ~ ., data = train_hor_yrs_x)

test_hor_yrs$Hormonal_Contraceptives_years <- predict(dt, newdata = test_hor_yrs_x)

hor_yrs_complete <- rbind(train_hor_yrs, test_hor_yrs)

df_impute$Hormonal_Contraceptives_years <- hor_yrs_complete$Hormonal_Contraceptives_years[order(rownames(hor_yrs_complete))]
table(df_impute$Hormonal_Contraceptives_years)
## 
##                 0              0.08              0.16              0.17 
##               262                25                16                 1 
##              0.25              0.33              0.41              0.42 
##                38                 9                 1                 8 
## 0.424825174825175               0.5              0.58              0.66 
##                32                25                 6                 6 
##              0.67              0.75                 1      1.2133822338 
##                 2                 7                77                 3 
##               1.5            1.6875  1.78200800189455                 2 
##                 3                 2                42                40 
##       2.282200521               2.5                 3               3.5 
##                 2                 1                36                 1 
##  3.62118644067797                 4               4.5                 5 
##                22                22                 1                33 
##                 6  6.25761904761905               6.5                 7 
##                24                 1                 1                21 
##                 8                 9                10                11 
##                18                12                11                 2 
##                12                13                14                15 
##                 4                 2                 2                 6 
##  [ reached getOption("max.print") -- omitted 6 entries ]

Missing Value Imputation for STDs

df_std <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs')

for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std[[i]]), decreasing = TRUE))[1]
  df_std[[i]][is.na(df_std[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  df_std[[i]][is.na(df_std[[i]])] <- median(df_std[[i]], na.rm = TRUE)
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std[] <- lapply(df_std, as.numeric)

df_std[x_features_categorical] <- lapply(df_std[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std <- df_std[!is.na(df_std$STDs), ]
test_std <- df_std[is.na(df_std$STDs), ]
train_std_x <- train_std[, !(names(train_std) == 'STDs')]
train_std_y <- train_std$STDs
test_std_x <- test_std[, !(names(test_std) == 'STDs')]
test_std_y <- test_std$STDs

dt <- rpart(train_std_y ~ ., data = train_std_x, method = "class")

test_std$STDs <- predict(dt, newdata = test_std_x, type = "class")

std_complete <- rbind(train_std, test_std)

df_impute$STDs <- std_complete$STDs[order(rownames(std_complete))]
table(df_impute$STDs)
## 
##   0   1 
## 762  76

Missing Value Imputation for STDs_Number

df_std_num <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_numerical <- setdiff(x_features_numerical, 'STDs_number')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_num[[i]]), decreasing = TRUE))[1]
  df_std_num[[i]][is.na(df_std_num[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_num[[i]], na.rm = TRUE)
  df_std_num[[i]][is.na(df_std_num[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_num[] <- lapply(df_std_num, as.numeric)

df_std_num[x_features_categorical] <- lapply(df_std_num[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_num <- subset(df_std_num, !is.na(STDs_number))
test_std_num <- subset(df_std_num, is.na(STDs_number))

train_std_num_x <- subset(train_std_num, select = -c(STDs_number))
train_std_num_y <- train_std_num$STDs_number

test_std_num_x <- subset(test_std_num, select = -c(STDs_number))
test_std_num_y <- test_std_num$STDs_number

std_model_num <- rpart(STDs_number ~ ., data = train_std_num, method = "anova")
test_std_num$STDs_number <- predict(std_model_num, newdata = test_std_num_x)
std_num_complete <- rbind(train_std_num, test_std_num)
df_impute$STDs_number <- std_num_complete$STDs_number[order(rownames(df_impute))]
table(df_impute$STDs_number)
## 
##                   0 0.00601503759398496                   1                   2 
##                 661                 101                  33                  36 
##                   3                   4 
##                   6                   1

Missing Value Imputation for STDs_condylomatosis

df_std_con <- df_impute[, !colnames(df_impute) %in% "Biopsy"]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_condylomatosis')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_con[[i]]), decreasing = TRUE))[1]
  df_std_con[[i]][is.na(df_std_con[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_con[[i]], na.rm = TRUE)
  df_std_con[[i]][is.na(df_std_con[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_con[] <- lapply(df_std_con, as.numeric)

df_std_con[x_features_categorical] <- lapply(df_std_con[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})
train_std_con <- df_std_con[!is.na(df_std_con$STDs_condylomatosis), ]

test_std_con <- df_std_con[is.na(df_std_con$STDs_condylomatosis), ]

train_std_con_x <- subset(train_std_con, select = -c(STDs_condylomatosis))
train_std_con_y <- train_std_con$STDs_condylomatosis

test_std_con_x <- subset(test_std_con, select = -c(STDs_condylomatosis))
test_std_con_y <- test_std_con$STDs_condylomatosis

std_model_con <- rpart(STDs_condylomatosis ~ ., data = train_std_con, method = "class")
test_std_con$STDs_condylomatosis <- predict(std_model_con, newdata = test_std_con_x, type = "class")
std_con_complete <- rbind(train_std_con, test_std_con)
df_impute$STDs_condylomatosis <- std_con_complete$STDs_condylomatosis[order(rownames(std_con_complete))]
table(df_impute$STDs_condylomatosis)
## 
##   0   1 
## 796  42

Missing Value Imputation for STDs_cervical_condylomatosis

df_std_cerv <- df_impute[, !colnames(df_impute) %in% "Biopsy"]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_cervical_condylomatosis')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_cerv[[i]]), decreasing = TRUE))[1]
  df_std_cerv[[i]][is.na(df_std_cerv[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_cerv[[i]], na.rm = TRUE)
  df_std_cerv[[i]][is.na(df_std_cerv[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_cerv[] <- lapply(df_std_cerv, as.numeric)

df_std_cerv[x_features_categorical] <- lapply(df_std_cerv[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_cerv <- df_std_cerv[!is.na(df_std_cerv$STDs_cervical_condylomatosis), ]
test_std_cerv <- df_std_cerv[is.na(df_std_cerv$STDs_cervical_condylomatosis), ]
train_std_cerv_x <- subset(train_std_cerv, select = -c(STDs_cervical_condylomatosis))
train_std_cerv_y <- train_std_cerv$STDs_cervical_condylomatosis
test_std_cerv_x <- subset(test_std_cerv, select = -c(STDs_cervical_condylomatosis))
test_std_cerv_y <- test_std_cerv$STDs_cervical_condylomatosis

std_model_cerv <- rpart(STDs_cervical_condylomatosis ~ ., data = train_std_cerv, method = "anova")
test_std_cerv$STDs_cervical_condylomatosis <- predict(std_model_cerv, newdata = test_std_cerv_x, type = "vector")
std_cerv_complete <- rbind(train_std_cerv, test_std_cerv)
df_impute$STDs_cervical_condylomatosis <- std_cerv_complete$STDs_cervical_condylomatosis[order(rownames(std_cerv_complete))]
table(df_impute$STDs_cervical_condylomatosis)
## 
##   0 
## 838

Missing Value Imputation for STDs_vaginal_condylomatosis

df_std_vagi <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_vaginal_condylomatosis')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_vagi[[i]]), decreasing = TRUE))[1]
  df_std_vagi[[i]][is.na(df_std_vagi[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_vagi[[i]], na.rm = TRUE)
  df_std_vagi[[i]][is.na(df_std_vagi[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_vagi[] <- lapply(df_std_vagi, as.numeric)

df_std_vagi[x_features_categorical] <- lapply(df_std_vagi[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_vagi <- subset(df_std_vagi, !is.na(STDs_vaginal_condylomatosis))
test_std_vagi <- subset(df_std_vagi, is.na(STDs_vaginal_condylomatosis))
train_std_vagi_x <- subset(train_std_vagi, select = -c(STDs_vaginal_condylomatosis))
train_std_vagi_y <- train_std_vagi$STDs_vaginal_condylomatosis
test_std_vagi_x <- subset(test_std_vagi, select = -c(STDs_vaginal_condylomatosis))
test_std_vagi_y <- test_std_vagi$STDs_vaginal_condylomatosis

dt <- rpart(train_std_vagi_y ~ ., data = train_std_vagi_x, method = "class")
test_std_vagi$STDs_vaginal_condylomatosis <- predict(dt, newdata = test_std_vagi_x, type = "class")
std_vagi_complete <- rbind(train_std_vagi, test_std_vagi)
df_impute$STDs_vaginal_condylomatosis <- std_vagi_complete$STDs_vaginal_condylomatosis[order(rownames(df_impute))]
table(df_impute$STDs_vaginal_condylomatosis)
## 
##   0   1 
## 834   4

Missing Value Imputation for STDs_vulvo_perineal_condylomatosis

df_std_peri <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_vulvo_perineal_condylomatosis')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_peri[[i]]), decreasing = TRUE))[1]
  df_std_peri[[i]][is.na(df_std_peri[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_peri[[i]], na.rm = TRUE)
  df_std_peri[[i]][is.na(df_std_peri[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_peri[] <- lapply(df_std_peri, as.numeric)

df_std_peri[x_features_categorical] <- lapply(df_std_peri[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_peri <- subset(df_std_peri, !is.na(STDs_vulvo_perineal_condylomatosis))
test_std_peri <- subset(df_std_peri, is.na(STDs_vulvo_perineal_condylomatosis))
train_std_peri_x <- subset(train_std_peri, select = -c(STDs_vulvo_perineal_condylomatosis))
train_std_peri_y <- train_std_peri$STDs_vulvo_perineal_condylomatosis
test_std_peri_x <- subset(test_std_peri, select = -c(STDs_vulvo_perineal_condylomatosis))
test_std_peri_y <- test_std_peri$STDs_vulvo_perineal_condylomatosis

dt <- rpart(train_std_peri_y ~ ., data = train_std_peri_x, method = "class")
test_std_peri$STDs_vulvo_perineal_condylomatosis <- predict(dt, newdata = test_std_peri_x, type = "class")
std_peri_complete <- rbind(train_std_peri, test_std_peri)
df_impute$STDs_vulvo_perineal_condylomatosis <- std_peri_complete$STDs_vulvo_perineal_condylomatosis[order(rownames(df_impute))]
table(df_impute$STDs_vulvo_perineal_condylomatosis)
## 
##   0   1 
## 797  41

Missing Value Imputation for STDs_syphilis

df_std_syp <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_syphilis')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_syp[[i]]), decreasing = TRUE))[1]
  df_std_syp[[i]][is.na(df_std_syp[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_syp[[i]], na.rm = TRUE)
  df_std_syp[[i]][is.na(df_std_syp[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_syp[] <- lapply(df_std_syp, as.numeric)

df_std_syp[x_features_categorical] <- lapply(df_std_syp[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_syp <- subset(df_std_syp, !is.na(STDs_syphilis))
test_std_syp <- subset(df_std_syp, is.na(STDs_syphilis))

train_std_syp_x <- subset(train_std_syp, select = -c(STDs_syphilis))
train_std_syp_y <- train_std_syp$STDs_syphilis

test_std_syp_x <- subset(test_std_syp, select = -c(STDs_syphilis))
test_std_syp_y <- test_std_syp$STDs_syphilis

dt <- rpart(train_std_syp_y ~ ., data = train_std_syp_x, method = "class")

test_std_syp$STDs_syphilis <- predict(dt, newdata = test_std_syp_x, type = "class")

std_syp_complete <- rbind(train_std_syp, test_std_syp)

df_impute$STDs_syphilis <- std_syp_complete$STDs_syphilis[order(rownames(df_impute))]
table(df_impute$STDs_syphilis)
## 
##   0   1 
## 821  17

Missing Value Imputation for STDs_pelvic_inflammatory_disease

df_std_pelv <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_pelvic_inflammatory_disease')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_pelv[[i]]), decreasing = TRUE))[1]
  df_std_pelv[[i]][is.na(df_std_pelv[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_pelv[[i]], na.rm = TRUE)
  df_std_pelv[[i]][is.na(df_std_pelv[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_pelv[] <- lapply(df_std_pelv, as.numeric)

df_std_pelv[x_features_categorical] <- lapply(df_std_pelv[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_pelv <- subset(df_std_pelv, !is.na(STDs_pelvic_inflammatory_disease))
test_std_pelv <- subset(df_std_pelv, is.na(STDs_pelvic_inflammatory_disease))

train_std_pelv_x <- subset(train_std_pelv, select = -c(STDs_pelvic_inflammatory_disease))
train_std_pelv_y <- train_std_pelv$STDs_pelvic_inflammatory_disease

test_std_pelv_x <- subset(test_std_pelv, select = -c(STDs_pelvic_inflammatory_disease))
test_std_pelv_y <- test_std_pelv$STDs_pelvic_inflammatory_disease

dt <- rpart(train_std_pelv_y ~ ., data = train_std_pelv_x, method = "class")

test_std_pelv$STDs_pelvic_inflammatory_disease <- predict(dt, newdata = test_std_pelv_x, type = "class")

std_pelv_complete <- rbind(train_std_pelv, test_std_pelv)

df_impute$STDs_pelvic_inflammatory_disease <- std_pelv_complete$STDs_pelvic_inflammatory_disease[order(rownames(df_impute))]
table(df_impute$STDs_pelvic_inflammatory_disease)
## 
##   0   1 
## 837   1

Missing Value Imputation for STDs_genital_herpes

df_std_geni <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_genital_herpes')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_geni[[i]]), decreasing = TRUE))[1]
  df_std_geni[[i]][is.na(df_std_geni[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_geni[[i]], na.rm = TRUE)
  df_std_geni[[i]][is.na(df_std_geni[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_geni[] <- lapply(df_std_geni, as.numeric)

df_std_geni[x_features_categorical] <- lapply(df_std_geni[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_geni <- subset(df_std_geni, !is.na(STDs_genital_herpes))
test_std_geni <- subset(df_std_geni, is.na(STDs_genital_herpes))

train_std_geni_x <- subset(train_std_geni, select = -c(STDs_genital_herpes))
train_std_geni_y <- train_std_geni$STDs_genital_herpes

test_std_geni_x <- subset(test_std_geni, select = -c(STDs_genital_herpes))
test_std_geni_y <- test_std_geni$STDs_genital_herpes

library(rpart)
dt <- rpart(train_std_geni_y ~ ., data = train_std_geni_x, method = "class")

test_std_geni$STDs_genital_herpes <- predict(dt, newdata = test_std_geni_x, type = "class")

std_geni_complete <- rbind(train_std_geni, test_std_geni)

df_impute$STDs_genital_herpes <- std_geni_complete$STDs_genital_herpes[order(rownames(df_impute))]
table(df_impute$STDs_genital_herpes)
## 
##   0   1 
## 837   1

Missing Value Imputation for STDs_molluscum_contagiosum

df_std_mollu <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_molluscum_contagiosum')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_mollu[[i]]), decreasing = TRUE))[1]
  df_std_mollu[[i]][is.na(df_std_mollu[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_mollu[[i]], na.rm = TRUE)
  df_std_mollu[[i]][is.na(df_std_mollu[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_mollu[] <- lapply(df_std_mollu, as.numeric)

df_std_mollu[x_features_categorical] <- lapply(df_std_mollu[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})


train_std_mollu <- subset(df_std_mollu, !is.na(STDs_molluscum_contagiosum))
test_std_mollu <- subset(df_std_mollu, is.na(STDs_molluscum_contagiosum))

train_std_mollu_x <- subset(train_std_mollu, select = -c(STDs_molluscum_contagiosum))
train_std_mollu_y <- train_std_mollu$STDs_molluscum_contagiosum

test_std_mollu_x <- subset(test_std_mollu, select = -c(STDs_molluscum_contagiosum))
test_std_mollu_y <- test_std_mollu$STDs_molluscum_contagiosum

dt <- rpart(train_std_mollu_y ~ ., data = train_std_mollu_x, method = "class")

test_std_mollu$STDs_molluscum_contagiosum <- predict(dt, newdata = test_std_mollu_x, type = "class")

std_mollu_complete <- rbind(train_std_mollu, test_std_mollu)

df_impute$STDs_molluscum_contagiosum <- std_mollu_complete$STDs_molluscum_contagiosum[order(rownames(df_impute))]
table(df_impute$STDs_molluscum_contagiosum )
## 
##   0   1 
## 837   1

Missing Value Imputation for STDs_AIDS

df_std_aids <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_AIDS')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_aids[[i]]), decreasing = TRUE))[1]
  
  df_std_aids[[i]][is.na(df_std_aids[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_aids[[i]], na.rm = TRUE)
  df_std_aids[[i]][is.na(df_std_aids[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_aids[] <- lapply(df_std_aids, as.numeric)

mode_value_STDs_AIDS <- names(sort(table(df_std_aids$STDs_AIDS), decreasing = TRUE))[1]
df_impute$STDs_AIDS[is.na(df_impute$STDs_AIDS)] <- mode_value_STDs_AIDS

table(df_impute$STDs_AIDS)
## 
##   0 0.0 
## 101 737

Missing Value Imputation for STDs_HIV

df_std_hiv <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_HIV')
for (i in x_features_categorical) {
  if (sum(!is.na(df_std_hiv[[i]])) > 0) {
    non_missing_values <- df_std_hiv[[i]][!is.na(df_std_hiv[[i]])]
    mode_value <- names(sort(table(non_missing_values), decreasing = TRUE))[1]
    df_std_hiv[[i]][is.na(df_std_hiv[[i]])] <- mode_value
  }
}

for (i in x_features_numerical) {
  median_value <- median(df_std_hiv[[i]], na.rm = TRUE)
  df_std_hiv[[i]][is.na(df_std_hiv[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_hiv[] <- lapply(df_std_hiv, as.numeric)

df_std_hiv[x_features_categorical] <- lapply(df_std_hiv[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_hiv <- subset(df_std_hiv, !is.na(STDs_HIV))
test_std_hiv <- subset(df_std_hiv, is.na(STDs_HIV))

train_std_hiv_x <- train_std_hiv[, !(names(train_std_hiv) == 'STDs_HIV')]
train_std_hiv_y <- train_std_hiv$STDs_HIV

test_std_hiv_x <- test_std_hiv[, !(names(test_std_hiv) == 'STDs_HIV')]
test_std_hiv_y <- test_std_hiv$STDs_HIV

library(rpart)
dt <- rpart(train_std_hiv_y ~ ., data = train_std_hiv_x, method = "class")

test_std_hiv$STDs_HIV <- predict(dt, newdata = test_std_hiv_x, type = "class")

std_hiv_complete <- rbind(train_std_hiv, test_std_hiv)

df_impute$STDs_HIV <- std_hiv_complete$STDs_HIV[order(rownames(df_impute))]

table(df_impute$STDs_HIV)
## 
##   0   1 
## 821  17

Missing Value Imputation for STDs_Hepatitis_B

df_std_hepa <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_Hepatitis_B')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_hepa[[i]]), decreasing = TRUE))[1]
  df_std_hepa[[i]][is.na(df_std_hepa[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_hepa[[i]], na.rm = TRUE)
  df_std_hepa[[i]][is.na(df_std_hepa[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_hepa[] <- lapply(df_std_hepa, as.numeric)

df_std_hepa[x_features_categorical] <- lapply(df_std_hepa[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_hepa <- subset(df_std_hepa, !is.na(STDs_Hepatitis_B))
test_std_hepa <- subset(df_std_hepa, is.na(STDs_Hepatitis_B))

train_std_hepa_x <- train_std_hepa[, !(names(train_std_hepa) == 'STDs_Hepatitis_B')]
train_std_hepa_y <- train_std_hepa$STDs_Hepatitis_B

test_std_hepa_x <- test_std_hepa[, !(names(test_std_hepa) == 'STDs_Hepatitis_B')]
test_std_hepa_y <- test_std_hepa$STDs_Hepatitis_B

library(rpart)
dt <- rpart(train_std_hepa_y ~ ., data = train_std_hepa_x, method = "class")

test_std_hepa$STDs_Hepatitis_B <- predict(dt, newdata = test_std_hepa_x, type = "class")

std_hepa_complete <- rbind(train_std_hepa, test_std_hepa)

df_impute$STDs_Hepatitis_B <- std_hepa_complete$STDs_Hepatitis_B[order(rownames(df_impute))]

table(df_impute$STDs_Hepatitis_B)
## 
##   0   1 
## 837   1

Missing Value Imputation for STDs_HPV

df_std_hpv <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_categorical <- setdiff(x_features_categorical, 'STDs_HPV')
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_std_hpv[[i]]), decreasing = TRUE))[1]
  df_std_hpv[[i]][is.na(df_std_hpv[[i]])] <- mode_value
}

for (i in x_features_numerical) {
  median_value <- median(df_std_hpv[[i]], na.rm = TRUE)
  df_std_hpv[[i]][is.na(df_std_hpv[[i]])] <- median_value
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
df_std_hpv[] <- lapply(df_std_hpv, as.numeric)

df_std_hpv[x_features_categorical] <- lapply(df_std_hpv[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_std_hpv <- subset(df_std_hpv, !is.na(STDs_HPV))
test_std_hpv <- subset(df_std_hpv, is.na(STDs_HPV))

train_std_hpv_x <- train_std_hpv[, !(names(train_std_hpv) == 'STDs_HPV')]
train_std_hpv_y <- train_std_hpv$STDs_HPV

test_std_hpv_x <- test_std_hpv[, !(names(test_std_hpv) == 'STDs_HPV')]
test_std_hpv_y <- test_std_hpv$STDs_HPV

library(rpart)
dt <- rpart(train_std_hpv_y ~ ., data = train_std_hpv_x, method = "class")

test_std_hpv$STDs_HPV <- predict(dt, newdata = test_std_hpv_x, type = "class")

std_hpv_complete <- rbind(train_std_hpv, test_std_hpv)

df_impute$STDs_HPV <- std_hpv_complete$STDs_HPV[order(rownames(df_impute))]

table(df_impute$STDs_HPV)
## 
##   0   1 
## 836   2

Missing Value Imputation for No_pregnancies

df_no_preg <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_numerical <- setdiff(x_features_numerical, 'No_pregnancies')
for (i in x_features_numerical) {
  df_no_preg[[i]][is.na(df_no_preg[[i]])] <- median(df_no_preg[[i]], na.rm = TRUE)
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_no_preg[[i]]), decreasing = TRUE))[1]
  df_no_preg[[i]][is.na(df_no_preg[[i]])] <- mode_value
}

df_no_preg[] <- lapply(df_no_preg, as.numeric)

df_no_preg[x_features_categorical] <- lapply(df_no_preg[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_no_preg <- subset(df_no_preg, !is.na(No_pregnancies))
test_no_preg <- subset(df_no_preg, is.na(No_pregnancies))

train_no_preg_x <- train_no_preg[, !(names(train_no_preg) == 'No_pregnancies')]
train_no_preg_y <- train_no_preg$No_pregnancies

test_no_preg_x <- test_no_preg[, !(names(test_no_preg) == 'No_pregnancies')]
test_no_preg_y <- test_no_preg$No_pregnancies

library(rpart)
dt <- rpart(train_no_preg_y ~ ., data = train_no_preg_x, method = "anova")

test_no_preg$No_pregnancies <- predict(dt, newdata = test_no_preg_x)

no_preg_complete <- rbind(train_no_preg, test_no_preg)

df_impute$No_pregnancies <- no_preg_complete$No_pregnancies[order(rownames(df_impute))]

table(df_impute$No_pregnancies)
## 
##                0                1 1.40329218106996 1.82352941176471 
##               14              263               22                2 
## 1.86363636363636                2 2.05405405405405                3 
##                2              234                9              136 
##           3.0125              3.1 3.47619047619048                4 
##               13                2                3               72 
## 4.55555555555556                5 5.83333333333333                6 
##                2               35                1               18 
##                7                8               10               11 
##                6                2                1                1

Missing Value Imputation for No_of_sex_partner

df_no_sexptnr <- df_impute[, !(names(df_impute) == 'Biopsy')]

x_features_numerical <- setdiff(x_features_numerical, 'No_of_sex_partner')
for (i in x_features_numerical) {
  df_no_sexptnr[[i]][is.na(df_no_sexptnr[[i]])] <- median(df_no_sexptnr[[i]], na.rm = TRUE)
}
## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA

## Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
## 参数不是数值也不是逻辑值:回覆NA
for (i in x_features_categorical) {
  mode_value <- names(sort(table(df_no_sexptnr[[i]]), decreasing = TRUE))[1]
  df_no_sexptnr[[i]][is.na(df_no_sexptnr[[i]])] <- mode_value
}

df_no_sexptnr[] <- lapply(df_no_sexptnr, as.numeric)

df_no_sexptnr[x_features_categorical] <- lapply(df_no_sexptnr[x_features_categorical], function(x) {
  x <- ifelse(x == 0, 'no', 'yes')
})

train_no_sexptnr <- subset(df_no_sexptnr, !is.na(No_of_sex_partner))
test_no_sexptnr <- subset(df_no_sexptnr, is.na(No_of_sex_partner))

train_no_sexptnr_x <- train_no_sexptnr[, !(names(train_no_sexptnr) == 'No_of_sex_partner')]
train_no_sexptnr_y <- train_no_sexptnr$No_of_sex_partner

test_no_sexptnr_x <- test_no_sexptnr[, !(names(test_no_sexptnr) == 'No_of_sex_partner')]
test_no_sexptnr_y <- test_no_sexptnr$No_of_sex_partner

library(rpart)
dt <- rpart(train_no_sexptnr_y ~ ., data = train_no_sexptnr_x, method = "anova")

test_no_sexptnr$No_of_sex_partner <- predict(dt, newdata = test_no_sexptnr_x)

no_sexptnr_complete <- rbind(train_no_sexptnr, test_no_sexptnr)

df_impute$No_of_sex_partner <- no_sexptnr_complete$No_of_sex_partner[order(rownames(df_impute))]

table(df_impute$No_of_sex_partner)
## 
##                1                2 2.05604719764012            2.275 
##              201              268               11                1 
## 2.78461538461538                3 3.38372093023256                4 
##               10              201                2               78 
##                5                6                7                8 
##               44                9                7                4 
##               10               28 
##                1                1

Check the empty rate

missing_counts <- colSums(is.na(df_impute))
print(missing_counts)
##                                Age                  No_of_sex_partner 
##                                  0                                  0 
##           First_sexual_intercourse                     No_pregnancies 
##                                  0                                  0 
##                             Smokes                         Smokes_yrs 
##                                  0                                  0 
##                    Smokes_packs_yr            Hormonal_Contraceptives 
##                                  0                                  0 
##      Hormonal_Contraceptives_years                                IUD 
##                                  0                                  0 
##                          IUD_years                               STDs 
##                                  0                                  0 
##                        STDs_number                STDs_condylomatosis 
##                                  0                                  0 
##       STDs_cervical_condylomatosis        STDs_vaginal_condylomatosis 
##                                  0                                  0 
## STDs_vulvo_perineal_condylomatosis                      STDs_syphilis 
##                                  0                                  0 
##   STDs_pelvic_inflammatory_disease                STDs_genital_herpes 
##                                  0                                  0 
##         STDs_molluscum_contagiosum                          STDs_AIDS 
##                                  0                                  0 
##                           STDs_HIV                   STDs_Hepatitis_B 
##                                  0                                  0 
##                           STDs_HPV               STDs_No_of_diagnosis 
##                                  0                                  0 
##                          Dx_Cancer                             Dx_CIN 
##                                  0                                  0 
##                             Dx_HPV                                 Dx 
##                                  0                                  0 
##                         Hinselmann                           Schiller 
##                                  0                                  0 
##                           Citology                             Biopsy 
##                                  0                                  0

Quick look at the Stats of the numerical features

summary(df_impute[c('Age', 'No_pregnancies', 'No_of_sex_partner',
                   'First_sexual_intercourse',
                   'Smokes_yrs',
                   'Smokes_packs_yr',
                   'STDs_No_of_diagnosis', 'Hormonal_Contraceptives_years', 'IUD_years', 'STDs_number')])
##       Age        No_pregnancies   No_of_sex_partner First_sexual_intercourse
##  Min.   :13.00   Min.   : 0.000   Min.   : 1.000    Length:838              
##  1st Qu.:20.00   1st Qu.: 1.000   1st Qu.: 2.000    Class :character        
##  Median :25.00   Median : 2.000   Median : 2.000    Mode  :character        
##  Mean   :26.81   Mean   : 2.287   Mean   : 2.511                            
##   Smokes_yrs        Smokes_packs_yr    STDs_No_of_diagnosis
##  Length:838         Length:838         Min.   :0.00000     
##  Class :character   Class :character   1st Qu.:0.00000     
##  Mode  :character   Mode  :character   Median :0.00000     
##                                        Mean   :0.08473     
##  Hormonal_Contraceptives_years  IUD_years          STDs_number    
##  Min.   : 0.000                Length:838         Min.   :0.0000  
##  1st Qu.: 0.000                Class :character   1st Qu.:0.0000  
##  Median : 0.580                Mode  :character   Median :0.0000  
##  Mean   : 2.218                                   Mean   :0.1523  
## [到达getOption("max.print") -- 略过2行]]

Save file to the specific road.

write.csv(df_impute, file = "D:/ivy/7004R/df_imputation.csv", row.names = FALSE)

Visualization

# Load necessary libraries
suppressWarnings({library(dplyr)
})
# Read the CSV file
df <- read.csv('D:/ivy/7004R/df_imputation.csv')

# Manually list categorical features
x_features_categorical <- c('Smokes', 'Hormonal_Contraceptives', 'IUD', 'STDs', 'STDs_condylomatosis',
                            'STDs_cervical_condylomatosis', 'STDs_vaginal_condylomatosis',
                            'STDs_vulvo_perineal_condylomatosis', 'STDs_syphilis',
                            'STDs_pelvic_inflammatory_disease', 'STDs_genital_herpes',
                            'STDs_molluscum_contagiosum', 'STDs_AIDS', 'STDs_HIV', 
                            'STDs_Hepatitis_B', 'STDs_HPV', 'Dx_Cancer', 'Dx_CIN', 
                            'Dx_HPV', 'Dx', 'Hinselmann', 'Citology', 'Biopsy')

# Identify numerical features
x_features_numerical <- setdiff(names(df), x_features_categorical)
# Assuming 'df' is already loaded and 'Biopsy' is a numeric column

# Convert 'Biopsy' to factor if it's numeric
df$Biopsy <- as.factor(df$Biopsy)

# Calculate the counts
biopsy_counts <- table(df$Biopsy)

# Create the pie chart
pie(biopsy_counts, 
    labels = paste0(round(100 * biopsy_counts / sum(biopsy_counts), 1), "%"), 
    main = "Biopsy Percentage",
    col = c("red", "green"),  # You can choose your colors
    cex = 1.5)  # Change font size as needed

# Add a legend, if desired
legend("topright", legend = names(biopsy_counts), fill = c("red", "green"))

** only 6.4% of the record have positive biopsy result i.e. people having cervical cancer.

install.packages("tidyverse")
## 程序包'tidyverse'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
suppressWarnings({
library(tidyverse)})
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.4
## ✔ lubridate 1.9.3     ✔ stringr   1.5.0
## ✔ purrr     1.0.2     ✔ tibble    3.2.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ magrittr::extract() masks tidyr::extract()
## ✖ dplyr::filter()     masks stats::filter()
## ✖ dplyr::lag()        masks stats::lag()
## ✖ purrr::lift()       masks caret::lift()
## ✖ purrr::set_names()  masks magrittr::set_names()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
x_features_categorical <- c('Smokes', 'Hormonal_Contraceptives', 'IUD', 'STDs', 'STDs_condylomatosis',
                            'STDs_cervical_condylomatosis', 'STDs_vaginal_condylomatosis',
                            'STDs_vulvo_perineal_condylomatosis', 'STDs_syphilis',
                            'STDs_pelvic_inflammatory_disease', 'STDs_genital_herpes',
                            'STDs_molluscum_contagiosum', 'STDs_AIDS', 'STDs_HIV', 
                            'STDs_Hepatitis_B', 'STDs_HPV', 'Dx_Cancer', 'Dx_CIN', 
                            'Dx_HPV', 'Dx', 'Hinselmann', 'Citology', 'Biopsy')  # Define your categorical features

# Loop through each categorical feature and create a count plot
for (i in x_features_categorical) {
  print(paste("Count Plot for", i))
  print(ggplot(df, aes_string(x = i)) +
        geom_bar(fill = "blue", color = "black") +
        theme_minimal() +
        labs(title = paste("Count Plot of", i), x = i, y = "Count"))
}
## [1] "Count Plot for Smokes"
## Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
## ℹ Please use tidy evaluation idioms with `aes()`.
## ℹ See also `vignette("ggplot2-in-packages")` for more information.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

## [1] "Count Plot for Hormonal_Contraceptives"

## [1] "Count Plot for IUD"

## [1] "Count Plot for STDs"

## [1] "Count Plot for STDs_condylomatosis"

## [1] "Count Plot for STDs_cervical_condylomatosis"

## [1] "Count Plot for STDs_vaginal_condylomatosis"

## [1] "Count Plot for STDs_vulvo_perineal_condylomatosis"

## [1] "Count Plot for STDs_syphilis"

## [1] "Count Plot for STDs_pelvic_inflammatory_disease"

## [1] "Count Plot for STDs_genital_herpes"

## [1] "Count Plot for STDs_molluscum_contagiosum"

## [1] "Count Plot for STDs_AIDS"

## [1] "Count Plot for STDs_HIV"

## [1] "Count Plot for STDs_Hepatitis_B"

## [1] "Count Plot for STDs_HPV"

## [1] "Count Plot for Dx_Cancer"

## [1] "Count Plot for Dx_CIN"

## [1] "Count Plot for Dx_HPV"

## [1] "Count Plot for Dx"

## [1] "Count Plot for Hinselmann"

## [1] "Count Plot for Citology"

## [1] "Count Plot for Biopsy"

# Example of loading from a CSV file
impute <- read.csv('D:/ivy/7004R/df_imputation.csv')

# Or if 'impute' is created within R
# impute <- data.frame(...)  # Replace with your dataframe creation code

# Assuming 'impute' is your dataframe and 'x_features_categorical' is a vector of categorical column names
impute[x_features_categorical] <- lapply(impute[x_features_categorical], function(x) ifelse(x == 0, 'no', 'yes'))
impute$Smokes_yrs <- as.numeric(impute$Smokes_yrs)
impute$IUD_years <- as.numeric(impute$IUD_years)
impute$Smokes_packs_yr <- as.numeric(impute$Smokes_packs_yr)
impute$smokes_yr_cat <- cut(impute$Smokes_yrs, breaks = c(-1, 2, 5, 10, 15, 20, 25, 50), labels = c('<2','2-5','5-10','10-15','15-20','20-25','>25'))
impute$smokepack_yr_cat <- cut(impute$Smokes_packs_yr, breaks = c(-1, 2, 5, 10, 20, 50), labels = c('<2','2-5','5-10','10-20','>20'))
impute$IUD_years_bin <- cut(impute$IUD_years, breaks = c(-1, 2, 4, 6, 8, 10, 15, 20), labels = c('<2','2-4','4-6','6-8','8-10','10-15','>15'))
impute$Hormonal_years_bin <- cut(impute$Hormonal_Contraceptives_years, breaks = c(-1, 2, 4, 6, 8, 10, 15, 20), labels = c('<2','2-4','4-6','6-8','8-10','10-15','>15'))
impute$Smokes_yrs <- NULL
impute$Smokes_packs_yr <- NULL
impute$IUD_years <- NULL
install.packages("ggplot2")
## Warning: 正在使用'ggplot2'这个程序包,因此不会被安装
install.packages("gridExtra")
## 程序包'gridExtra'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
suppressWarnings({library(ggplot2)
library(gridExtra)})
## 
## 载入程辑包:'gridExtra'
## The following object is masked from 'package:dplyr':
## 
##     combine
vars <- c('Dummy', 'STDs_condylomatosis', 'STDs_cervical_condylomatosis', 
          'STDs_vaginal_condylomatosis', 'STDs_vulvo_perineal_condylomatosis', 
          'STDs_syphilis', 'STDs_pelvic_inflammatory_disease', 'STDs_genital_herpes', 
          'STDs_molluscum_contagiosum', 'STDs_AIDS', 'STDs_HIV', 
          'STDs_Hepatitis_B', 'STDs_HPV')

plot_list <- list()
for (i in 2:length(vars)) {
  plot_list[[i-1]] <- ggplot(impute, aes_string(x = vars[i], y = 'Age', color = 'Biopsy')) +
                      geom_boxplot() +
                      labs(title = paste('Biopsy &', vars[i]), x = vars[i], y = 'Age of the Patient') +
                      theme_minimal()+
                      theme(text = element_text(size = 8))
}
do.call("grid.arrange", c(plot_list, ncol = 3))

** In all the plots we can clearly the person with higher age are prone to be tested as Positive in Biopsy test

4. Classification Problem

Loading required packages

suppressWarnings({install.packages("tidyverse")
install.packages("ggplot2")
install.packages("caret")
install.packages("rpart")
install.packages("pROC")
install.packages("randomForest")
install.packages("e1071")
install.packages("kernlab")
install.packages("naivebayes")
install.packages("reticulate")
install.packages("ROSE")
install.packages("glmnet")
install.packages("caretEnsemble")
install.packages("MLmetrics")
install.packages("xgboost")
install.packages("shapper")
library(xgboost)
library(shapper)
library(tidyverse)  
library(ggplot2)    
library(caret)     
library(rpart)  
library(pROC)
library(randomForest) 
library(e1071)      
library(kernlab)    
library(naivebayes) 
library(naivebayes) 
library(reticulate)       
library(glmnet)     
library(caretEnsemble)
library(MLmetrics)
library(xgboost)
library(shapper)
})
## 程序包'pROC'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'randomForest'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'e1071'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'kernlab'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'naivebayes'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'reticulate'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'ROSE'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'glmnet'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'caretEnsemble'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'MLmetrics'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'xgboost'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 程序包'shapper'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
## 
## 载入程辑包:'xgboost'
## The following object is masked from 'package:dplyr':
## 
##     slice
## Type 'citation("pROC")' for a citation.
## 
## 载入程辑包:'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## 载入程辑包:'randomForest'
## The following object is masked from 'package:gridExtra':
## 
##     combine
## The following object is masked from 'package:dplyr':
## 
##     combine
## The following object is masked from 'package:ggplot2':
## 
##     margin
## 
## 载入程辑包:'kernlab'
## The following object is masked from 'package:purrr':
## 
##     cross
## The following object is masked from 'package:ggplot2':
## 
##     alpha
## naivebayes 0.9.7 loaded
## 载入需要的程辑包:Matrix
## 
## 载入程辑包:'Matrix'
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## Loaded glmnet 4.1-8
## 
## 载入程辑包:'caretEnsemble'
## The following object is masked from 'package:ggplot2':
## 
##     autoplot
## 
## 载入程辑包:'MLmetrics'
## The following objects are masked from 'package:caret':
## 
##     MAE, RMSE
## The following object is masked from 'package:base':
## 
##     Recall

loading dataset

df <- read.csv("D:/ivy/7004R/df_imputation.csv")
# Assuming 'df' is a data frame in R
df <- data.frame(df)
df <- data.frame(lapply(df, as.numeric))  # Convert to float64

x <- df[, !(names(df) %in% c('Biopsy'))]
y <- df$Biopsy

# Standardize the features
x_scaled <- scale(x)

# Split the dataset
set.seed(11)  # Set seed for reproducibility
split_index <- createDataPartition(y, p = 0.7, list = FALSE)
x_train <- x[split_index, ]
y_train <- y[split_index]
x_test <- x[-split_index, ]
y_test <- y[-split_index]

# Standardize the features for the split dataset
x_train_scaled <- scale(x_train)
x_test_scaled <- scale(x_test)

# List to store various model metrics
l <- list()

Build classification models

#Logistic Regression
suppressWarnings({
library(caret)
models_lr <- function(x, y, x_test, y_test) {
  mod <- list()
  model <- glm(y ~ ., data = cbind(y, x), family = binomial)
  ypred <- ifelse(predict(model, newdata = cbind(y_test, x_test), type = "response") > 0.5, 1, 0)
  mod$Model <- 'LogisticRegression'
  mod$Train_Score <- sum((predict(model, newdata = cbind(y_train, x_train), type = "response") > 0.5) %in% y_train) / length(y_train)
  mod$Test_accuracy <- sum(ypred == y_test) / length(y_test)
  mod$f1score <- F1_Score(y_test, ypred)
  mod$recall <- Recall(y_test, ypred)
  mod$precision <- Precision(y_test, ypred)
  mod$roc_auc <- AUC(y_test, ypred)
  return(mod)
}
})
# Decision Tree
models_dt <- function(x, y, x_test, y_test) {
  mod <- list()
  model <- rpart(y ~ ., data = as.data.frame(cbind(y, x)), method = "class")
  ypred <- ifelse(predict(model, newdata = as.data.frame(x_test), type = "class") == 1, 1, 0)
  mod$Model <- 'Decision Tree'
  mod$Train_Score <- sum(predict(model, newdata = as.data.frame(x_train), type = "class") == y_train) / length(y_train)
  mod$Test_accuracy <- sum(ypred == y_test) / length(y_test)
  mod$f1score <- F1_Score(y_test, ypred)
  mod$recall <- Recall(y_test, ypred)
  mod$precision <- Precision(y_test, ypred)
  mod$roc_auc <- AUC(y_test, ypred)
  return(mod)
}
# Random Forest

models_rf <- function(x, y, x_test, y_test) {
  mod <- list()
  model <- randomForest(y ~ ., data = cbind(y, x), ntree = 100)
  ypred <- predict(model, newdata = cbind(y_test, x_test), type = "response")
  ypred <- ifelse(ypred > 0.5, 1, 0)
  mod$Model <- 'Random Forest'
  mod$Train_Score <- sum(as.numeric(predict(model, newdata = cbind(y_train, x_train), type = "response")) > 0.5 %in% as.numeric(y_train)) / length(y_train)
  mod$Test_accuracy <- sum(as.numeric(ypred) == as.numeric(y_test)) / length(y_test)
  mod$f1score <- F1_Score(as.numeric(y_test), as.numeric(ypred))
  mod$recall <- Recall(as.numeric(y_test), as.numeric(ypred))
  mod$precision <- Precision(as.numeric(y_test), as.numeric(ypred))
  mod$roc_auc <- AUC(as.numeric(y_test), as.numeric(ypred))
  return(mod)
}
# Naive Bayes
library(e1071)
library(pROC)
models_nb <- function(x, y, x_test, y_test) {
  mod <- list()
 #model <- naiveBayes(x, y)
  model <- naiveBayes(y ~ ., data = data.frame(cbind(y, x)))
  ypred <- predict(model, newdata = x_test)
  mod$Model <- 'GaussianNB'
  mod$Train_Score <- sum(predict(model, newdata = x_train) == y_train) / length(y_train)
  mod$Test_accuracy <- sum(ypred == y_test) / length(y_test)
  mod$f1score <- F1_Score(y_test, ypred)
  mod$recall <- Recall(y_test, ypred)
  mod$precision <- Precision(y_test, ypred)
  mod$roc_auc <- auc(roc(y_test, as.numeric(ypred)))
  
  return(mod)
}

Evaluation Metrics :

suppressWarnings({
l[[1]] <- models_lr(x_train, y_train, x_test, y_test)
l[[2]] <- models_dt(x_train, y_train, x_test, y_test)
l[[3]] <- models_rf(x_train, y_train, x_test, y_test)  
l[[4]] <- models_nb(x_train, y_train, x_test, y_test)
})
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
base_df <- do.call(rbind, l)
base_df <- base_df[, -2]
base_df
##      Model                Test_accuracy f1score    recall     precision
## [1,] "LogisticRegression" 0.9442231     0.9702128  0.9702128  0.9702128
## [2,] "Decision Tree"      0.9561753     0.9767442  0.9829787  0.9705882
## [3,] "Random Forest"      0.9681275     0.982906   0.9787234  0.9871245
## [4,] "GaussianNB"         0.1035857     0.08163265 0.04255319 1        
##      roc_auc  
## [1,] 0.7663564
## [2,] 0.831448 
## [3,] 0.8546733
## [4,] 0.5212766
install.packages("ggplot2")
## Warning: 正在使用'ggplot2'这个程序包,因此不会被安装
results <- data.frame(
  Model = character(0),
  Metric = character(0),
  Value = numeric(0)
)

models <- list(models_lr, models_dt, models_rf, models_nb)
for (i in 1:length(models)) {
  model_result <- models[[i]](x_train, y_train, x_test, y_test)
  model_name <- model_result$Model
  
# Added accuracy, F1 score, recall, Accuracy and ROC AUC
  
  metrics <- c("Test_accuracy", "f1score", "recall", "precision", "roc_auc")
  for (metric in metrics) {
    value <- model_result[[metric]]
    results <- rbind(results, data.frame(Model = model_name, Metric = metric, Value = value))
  }
}
## Warning: glm.fit:拟合機率算出来是数值零或一
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases

## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
library(ggplot2)


ggplot(results, aes(x = Metric, y = Value, color = Model, group = Model)) +
  geom_line() +
  labs(title = "Model Evaluation Metrics Comparison",
       x = "Metric",
       y = "Value") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_color_manual(values = c("LogisticRegression" = "blue", "Decision Tree" = "green", "Random Forest" = "orange", "GaussianNB" = "red"))

1.Accuracy : Ratio of correctly predicted observation to the total observations. It is a great measure but only when you have symmetric datasets where values of false positive and false negatives are almost same. 2.Precision : The ratio of correctly predicted positive observations to the total predicted positive observations. 3.Recall (Sensitivity) : The ratio of correctly predicted positive observations to the all observations in actual class - yes. 4.F1 Score : The weighted average of Precision and Recall 5.ROC score : Measures how well the model can segragate the target classes. Base Model Conclusion: This involves handling sensitive medical data, where prioritizing Recall is crucial,we have to predict actual cancer patients as cancer patient accurately.

We choose “Random Forest” and “Decision Tree” models as our best model. This decision is based on the higher recall and ROC_AUC scores, and it seems to be no apparent overfitting. (Logistic Regression Train_Score: 1 Possibly overfitting) Further feature extraction will be carried out based on the Random Forest model.

#Feature selection
library(randomForest)
library(ggplot2)
suppressWarnings({
model <- randomForest(x, y)
feature_importance <- importance(model)
feature_importance <- feature_importance[order(-feature_importance), ]
})
feature_importance_df <- data.frame(
  Feature = names(feature_importance),
  Importance = unlist(feature_importance)
)

feature_importance_df <- feature_importance_df[order(-feature_importance_df$Importance), ]
feature_importance_df$Percentage <- feature_importance_df$Importance / sum(feature_importance_df$Importance) * 100

library(ggplot2)

ggplot(data = feature_importance_df, aes(y = reorder(Feature, Importance), x = Importance)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  geom_text(aes(label = sprintf("%.2f%%", Percentage)), hjust = -0.2, size = 3, color = "black") +
  labs(title = "Feature Importance Plot", y = "Feature", x = "Importance") +
  theme_minimal() +
  theme(panel.background = element_rect(fill = "lightblue"))

We choose to discard the bottom 6 columns of features, each accounting for less than 0.01%.

# List to store various model metrics
l_feature <- list()
l_feature[[1]] <- models_dt(x_train, y_train, x_test, y_test) 
#delete 6 columns
columns_to_remove <- c("STDs_vaginal_condylomatosis", "STDs_Hepatitis_B", "STDs_genital_herpes",
                       "STDs_molluscum_contagiosum", "STDs_cervical_condylomatosis", "STDs_AIDS")


# Split the dataset
#set.seed(111)  # Set seed for reproducibility
# From x drop sepecific columns
x_feature <- x[, setdiff(names(x), columns_to_remove)]
# Standardize the features
x_feature_scaled <- scale(x_feature)
#split_index <- createDataPartition(y, p = 0.7, list = FALSE)
x_feature_train <- x_feature[split_index, ]
#y_train <- y[split_index]
x_feature_test <- x_feature[-split_index, ]
#y_test <- y[-split_index]
# Standardize the features for the split dataset
x_feature_train_scaled <- scale(x_feature_train)
x_feature_test_scaled <- scale(x_feature_test)

#rebuild model

# Decision Tree
models_dt_f <- function(x_feature, y, x_feature_test, y_test) {
  mod <- list()
  model <- rpart(y ~ ., data = as.data.frame(cbind(y, x_feature)), method = "class")
  ypred <- ifelse(predict(model, newdata = as.data.frame(x_feature_test), type = "class") == 1, 1, 0)
  mod$Model <- 'Decision Tree'
  mod$Train_Score <- sum(predict(model, newdata = as.data.frame(x_feature_train), type = "class") == y_train) / length(y_train)
  mod$Test_accuracy <- sum(ypred == y_test) / length(y_test)
  mod$f1score <- F1_Score(y_test, ypred)
  mod$recall <- Recall(y_test, ypred)
  mod$precision <- Precision(y_test, ypred)
  mod$roc_auc <- AUC(y_test, ypred)
  return(mod)
}
l_feature[[2]]<- models_dt_f(x_feature_train, y_train, x_feature_test, y_test)  
# Random Forest
suppressWarnings({
models_rf_f <- function(x_feature, y, x_feature_test, y_test) {
  mod <- list()
  model <- randomForest(y ~ ., data = cbind(y, x_feature), ntree = 100)
  ypred <- predict(model, newdata = cbind(y_test, x_feature_test), type = "response")
  ypred <- ifelse(ypred > 0.5, 1, 0)
  mod$Model <- 'Random Forest'
  mod$Train_Score <- sum(as.numeric(predict(model, newdata = cbind(y_train, x_feature_train), type = "response")) > 0.5 %in% as.numeric(y_train)) / length(y_train)
  mod$Test_accuracy <- sum(as.numeric(ypred) == as.numeric(y_test)) / length(y_test)
  mod$f1score <- F1_Score(as.numeric(y_test), as.numeric(ypred))
  mod$recall <- Recall(as.numeric(y_test), as.numeric(ypred))
  mod$precision <- Precision(as.numeric(y_test), as.numeric(ypred))
  mod$roc_auc <- AUC(as.numeric(y_test), as.numeric(ypred))
  return(mod)
}
l_feature[[3]] <- models_rf(x_train, y_train, x_test, y_test) 
l_feature[[4]]<- models_rf_f(x_feature_train, y_train, x_feature_test, y_test)  
base_df_f <- do.call(rbind, l_feature)})
base_df_f[2, 1] <- "Decision Tree (after select features)"
base_df_f[4, 1] <- "Random Forest (after select features)"
base_df_f<-base_df_f[,-2]
base_df_f
##      Model                                   Test_accuracy f1score   recall   
## [1,] "Decision Tree"                         0.9561753     0.9767442 0.9829787
## [2,] "Decision Tree (after select features)" 0.9561753     0.9767442 0.9829787
## [3,] "Random Forest"                         0.9561753     0.9766454 0.9787234
## [4,] "Random Forest (after select features)" 0.9641434     0.9808917 0.9829787
##      precision roc_auc  
## [1,] 0.9705882 0.831448 
## [2,] 0.9705882 0.831448 
## [3,] 0.9745763 0.8206215
## [4,] 0.9788136 0.8560734

In cervical cancer diagnosis tasks, a higher emphasis should be placed on recall to ensure that as many patients as possible are correctly diagnosed as positive, aiming to minimize the rate of false negatives.

After selecting features, the Random Forest model’s is the best one. the Random Forest model’s recall (True Positive Rate) has improved from 0.9787234 to 0.987234.

The ROC AUC has increased slightly from 0.8443942 to 0.8560734 Additionally, the F1 Score increased slightly, even though the f1score and precision is decreased slightly, it’s worthwhile. The improvements in these metrics collectively indicate an enhanced model performance, with better recall, f1score,roc_auc and discrimination capability after the feature selection process.


5. Regression Problem

Question: How can we predict the Number of pregnancies of patients with reported cervical cancer?

Problem: Predicting Number of Pregnancies of people with reported cervical cancer

Objective: To predict the Number of Pregnancies of patients with reported cervical cancer, aiming for performance above the R-square threshold 0.75 and below the Mean Square Error threshold of 1.

Target Variable: Number of pregnancies (Continuous Numerical Variable)

Data subset: Patients with Biopsy Result 1, indicating presence of cervical cancer

Loading libraries

install.packages("neuralnet")
## 程序包'neuralnet'打开成功,MD5和检查也通过
## 
## 下载的二进制程序包在
##  C:\Users\Ivy\AppData\Local\Temp\Rtmp2pmDZs\downloaded_packages里
suppressWarnings({
library(tidyverse)
library(caret)
library(xgboost)
library(rpart)
library(randomForest)
library(e1071)
library(neuralnet)
})
## 
## 载入程辑包:'neuralnet'
## The following object is masked from 'package:dplyr':
## 
##     compute

Loading Cleaned Data

df <- read.csv("D:/ivy/7004R/df_imputation.csv")
df <- data.frame(df)

Filter to keep only patients with cervical cancer

i.e. Biopsy report is positive for cervical cancer

biopsy1 <- df %>%
  filter(Biopsy == 1)

Model Construction:

Split dataset into X features and target variable Y

X <- biopsy1 %>%
  select(-No_pregnancies)

y <- biopsy1$No_pregnancies

Set training and testing set: 70% Training | 30% Testing

# Seed for random Number generator in R for reproducibility
set.seed(42)
partitiondata <- createDataPartition(y, p = 0.7, list = FALSE)
xtraining <- X[partitiondata, ]
ytraining <- y[partitiondata]
xtesting <- X[-partitiondata, ]
ytesting <- y[-partitiondata]

Training the models & make predictions on testing set

Support Vector Regression

svm_preg_model <- svm(No_pregnancies ~ ., data = biopsy1)
## Warning in svm.default(x, y, scale = scale, ..., na.action = na.action):
## Variable(s) 'STDs_cervical_condylomatosis' and 'STDs_vaginal_condylomatosis'
## and 'STDs_pelvic_inflammatory_disease' and 'STDs_genital_herpes' and
## 'STDs_molluscum_contagiosum' and 'STDs_AIDS' and 'STDs_HIV' and
## 'STDs_Hepatitis_B' and 'Biopsy' constant. Cannot scale data.
svm_predictions <- predict(svm_preg_model, newdata = xtesting)

Linear Regression

lm_preg_model <- lm(No_pregnancies ~ ., data = biopsy1)
lm_predictions <- predict(lm_preg_model, newdata = xtesting)
## Warning in predict.lm(lm_preg_model, newdata = xtesting): prediction from
## rank-deficient fit; attr(*, "non-estim") has doubtful cases

Decision Tree Regressor

tree_preg_model <- rpart(formula = No_pregnancies ~ ., data = biopsy1)
tree_predictions <- predict(tree_preg_model, newdata = xtesting)

Random Forest Regressor

rf_preg_model <- randomForest(No_pregnancies ~ ., data = biopsy1)
rf_predictions <- predict(rf_preg_model, newdata = xtesting)

Model Evaluation: MSE, RMSE, MAE & R-squared

# Calculate MSE, RMSE, MAE & R-squared
# Support Vector Machine
svm_mse <- mean((svm_predictions - ytesting)^2) 
svm_rmse <- sqrt(svm_mse)
svm_mae <- mean(abs(svm_predictions - ytesting))
svm_r2 <- 1 - svm_mse / var(ytesting)

# Linear Regression
lm_mse <- mean((lm_predictions - ytesting)^2) 
lm_rmse <- sqrt(lm_mse)
lm_mae <- mean(abs(lm_predictions - ytesting))
lm_r2 <- 1 - lm_mse / var(ytesting)

# Decision Tree
tree_mse <- mean((tree_predictions - ytesting)^2) 
tree_rmse <- sqrt(tree_mse)
tree_mae <- mean(abs(tree_predictions - ytesting))
tree_r2 <- 1 - tree_mse / var(ytesting)

# Random Forest Regressor
rf_mse <- mean((rf_predictions - ytesting)^2) 
rf_rmse <- sqrt(rf_mse)
rf_mae <- mean(abs(rf_predictions - ytesting))
rf_r2 <- 1 - rf_mse / var(ytesting)

# Display as a dataframe
evaluation1 <- data.frame(
  Metric = c("MSE: Mean Square Error", "RMSE: Root Mean Square Error", "MAE: Mean Absolution Error", "R-squared"),
  SupportVectorMachine = c(svm_mse, svm_rmse, svm_mae, svm_r2),
  LinearRegression = c(lm_mse, lm_rmse, lm_mae, lm_r2)
)
evaluation2 <- data.frame(
  Metric = c("MSE: Mean Square Error", "RMSE: Root Mean Square Error", "MAE: Mean Absolution Error", "R-squared"),
  DecisionTree = c(tree_mse, tree_rmse, tree_mae, tree_r2),
  RandomForest = c(rf_mse, rf_rmse, rf_mae, rf_r2)
)
evaluation1
##                         Metric SupportVectorMachine LinearRegression
## 1       MSE: Mean Square Error            1.2304328        1.0287917
## 2 RMSE: Root Mean Square Error            1.1092487        1.0142937
## 3   MAE: Mean Absolution Error            0.7409388        0.7823610
## 4                    R-squared            0.4893461        0.5730311
evaluation2
##                         Metric DecisionTree RandomForest
## 1       MSE: Mean Square Error    1.2197130    0.4733616
## 2 RMSE: Root Mean Square Error    1.1044062    0.6880128
## 3   MAE: Mean Absolution Error    0.7977321    0.5698323
## 4                    R-squared    0.4937950    0.8035456

Support Vector Machine and Decision Tree perform similarly, especially the three metrics with about 1.2 MSE, 1.1 RMSE, and 0.49 R-squared. Linear Regression out-performs both in the same metrics with lower MSE value and higher R-square value.

However, Random Forest significantly out-performs all the models, on all four metrics. It has the lowest scores of MSE, RMSE and MAE, which demonstrates that it has the smallest differences between actual and predicted values.

Random Forest Regressor also has the highest R-square value of 0.80, indicating the highest explained variance, which highlights it as the best model among the models in the evaluation.


Final Model : Random Forest Regressor

plot(ytesting, rf_predictions, main = "Predicted VS Actual No. of Pregnancies", xlab = "Actual No. of Pregnancies", ylab = "Predicted No. of Pregnancies", col = "steelblue", pch = 16, cex = 1.5)

abline(0, 1, col = "skyblue", lty = 2, lwd = 2)

legend("bottomright", legend = c("Actual VS Predicted", "Best Fit Line"), col = c("steelblue", "skyblue"), pch = c(16, NA), lty = c(NA, 2), lwd = c(1.5, 2), inset = c(0, 0.05))

suppressWarnings({
# Feature Importance Plot for RF
f_imp <- rf_preg_model$importance[, 1]
var_names <- rownames(f_imp)
barplot(f_imp, names.arg = var_names, main = "Feature Importance Plot for Random Forest Regressor", col = "skyblue")

# Feature Importance Highlights for RF
age_imp <- f_imp["Age"]
hcyears_imp <- f_imp["Hormonal_Contraceptives_years"]

highlights <- data.frame(Feature = c("Age", "Hormonal Contraceptives (years)"), Importance = c(age_imp, hcyears_imp))

barplot(highlights$Importance, names.arg = highlights$Feature, main = "Feature Importance Highlights", col = "steelblue")

})


From the charts we can deduce that the factors that most affect number of pregnancies in cervical cancer reported patients are the Age and Hormonal contraceptives usage in years.

This suggests that healthcare professionals may need to be cautious of these factors in patients who suffer from cervical cancer.

It can help provide insight into cervical cancer patient’s reproductive health, fertility and allow for preparation and guidance in family planning.

There is also valuable insights on what we can focus on for future works within this scope of the healthcare domain.


Conclusion on Regression Model

Our objective was to predict the Number of Pregnancies of cervical-cancer-positive patients. The aim was achieving performance metrics above the R-square threshold, 0.75, and below the Mean Square Error threshold, 1, in order to produce accurate predictions and gather valuable insights in this specific healthcare domain.

As the Random Forest Regressor achieved the R-square value of 0.80 and Mean Square Error of 0.47, both meeting the criteria for our objective, we can consider it achieved.

7. Conclusion