R Markdown

  1. Tiền xử lí số liệu
  1. Gọi các thư viện cần thiết
library(wordcloud)
## Warning: package 'wordcloud' was built under R version 4.3.2
## Loading required package: RColorBrewer
library(broom)
## Warning: package 'broom' was built under R version 4.3.2
library(car)
## Warning: package 'car' was built under R version 4.3.2
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.3.2
library(lessR)
## Warning: package 'lessR' was built under R version 4.3.2
## 
## lessR 4.3.0                         feedback: gerbing@pdx.edu 
## --------------------------------------------------------------
## > d <- Read("")   Read text, Excel, SPSS, SAS, or R data file
##   d is default data frame, data= in analysis routines optional
## 
## Learn about reading, writing, and manipulating data, graphics,
## testing means and proportions, regression, factor analysis,
## customization, and descriptive statistics from pivot tables
##   Enter:  browseVignettes("lessR")
## 
## View changes in this and recent versions of lessR
##   Enter: news(package="lessR")
## 
## Interactive data analysis
##   Enter: interact()
## 
## Attaching package: 'lessR'
## The following objects are masked from 'package:car':
## 
##     bc, recode, sp
library(car)
library(ggpubr)
## Loading required package: ggplot2
library(corpustools)
# For ROC curve to evaluate model
library(ResourceSelection)
## ResourceSelection 0.3-6      2023-06-27
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::recode() masks lessR::recode(), car::recode()
## ✖ dplyr::rename() masks lessR::rename()
## ✖ purrr::some()   masks car::some()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(SnowballC)
# Loading package
library(caTools)
library(ROCR)
library(e1071)
## 
## Attaching package: 'e1071'
## 
## The following object is masked from 'package:lessR':
## 
##     kurtosis
library(doSNOW)
## Loading required package: foreach
## 
## Attaching package: 'foreach'
## 
## The following objects are masked from 'package:purrr':
## 
##     accumulate, when
## 
## Loading required package: iterators
## Loading required package: snow
library(caret)
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(quanteda)
## Package version: 3.3.1
## Unicode version: 15.1
## ICU version: 74.1
## Parallel computing: 4 of 4 threads used.
## See https://quanteda.io for tutorials and examples.
library(irlba)
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## 
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
library(tm)
## Loading required package: NLP
## 
## Attaching package: 'NLP'
## 
## The following objects are masked from 'package:quanteda':
## 
##     meta, meta<-
## 
## The following object is masked from 'package:ggplot2':
## 
##     annotate
## 
## 
## Attaching package: 'tm'
## 
## The following object is masked from 'package:quanteda':
## 
##     stopwords
library(dplyr)
library(lubridate)
library(dplyr)
library(readr)
library(stringr)
library(ggplot2)
  1. Đọc file dữ liệu dirty_data.csv
dat=read.csv("D:/Probability and Statistics/BTL/dirty_data.csv",stringsAsFactors = FALSE)

Xem bảng số liệu của dirty_data.csv

View(dat)
head(dat)
  1. Kiểm tra dữ liệu khuyết
sum(is.na(dat)) 
## [1] 0
  1. Trích ra tập dữ liệu new_dat chỉ chứa các biến chính.
new_dat<-dat[c(1,6,10,15,16)]

Xem bảng số liệu của new_dat

View(new_dat)
head(new_dat)
  1. Phân tích, sửa lỗi, thêm các biến
    5.1. Xử lí lỗi kiểu dữ liệu: Xem kiểu dữ liệu của các biến trong file new_dat
sapply(new_dat,class)
##               order_id            order_price        coupon_discount 
##            "character"              "integer"              "integer" 
## latest_customer_review      is_happy_customer 
##            "character"            "character"
 5.1.1. Biến order_price
#Đổi kiểu dữ liệu cho biến order_price thành numeric
new_dat$order_price<-as.numeric(new_dat$order_price)
# Xử lí các outliers
#Thay thế các vị trí outliers bằng giá trị trung bình của biến order_price
new_dat<-new_dat%>%
  mutate(order_price=ifelse(order_price>quantile(order_price,0.75,na.rm=T)+1.5*IQR(order_price,na.rm=T)|order_price<quantile(order_price,0.25,na.rm=T)-1.5*IQR(order_price,na.rm=T),mean(order_price,na.rm=T),order_price))
 5.1.2. Biến is_happy_customer
# Đổi TRUE FALSE trong biến is_happy_customer thành 0: FALSE; TRUE:1
new_dat$is_happy_customer <- as.integer(as.logical(new_dat$is_happy_customer))
 5.1.3. Biến coupon_discount
#Đổi kiểu dữ liệu cho biến coupon_discount thành numeric
new_dat$coupon_discount<-as.numeric(new_dat$coupon_discount)
5.2. Tạo dữ liệu mới


5.2.1. Tạo dữ liệu new_df từ tập dữ liệu new_dat. Tập dữ liệu được dùng để dự đoán sự hài lòng của khách hàng

new_df<-new_dat[c(1,4,5)]
new_df$is_happy_customer <- as.factor(new_df$is_happy_customer)
View(new_df)
head(new_df)
 5.2.2. Tạo tập dữ liệu data_anova cho bài toán ANOVA 1 nhân tố
Coupon_0 <- subset(new_dat, coupon_discount == 0)
Coupon_5 <- subset(new_dat, coupon_discount == 5)
Coupon_10 <- subset(new_dat, coupon_discount == 10)
Coupon_15 <- subset(new_dat, coupon_discount == 15)
Coupon_25 <- subset(new_dat, coupon_discount == 25)


Order_price_coupon_0 <- Coupon_0[, c("order_price", "coupon_discount")]
Order_price_coupon_5 <- Coupon_5[, c("order_price", "coupon_discount")]
Order_price_coupon_10 <- Coupon_10[, c("order_price", "coupon_discount")]
Order_price_coupon_15 <- Coupon_15[, c("order_price", "coupon_discount")]
Order_price_coupon_25 <- Coupon_25[, c("order_price", "coupon_discount")]

data_anova <- rbind(
  data.frame(order_price = Order_price_coupon_0$order_price, group = 'Coupon_0'),
  data.frame(order_price = Order_price_coupon_5$order_price, group = 'Coupon_5'),
  data.frame(order_price = Order_price_coupon_10$order_price, group = 'Coupon_10'),
  data.frame(order_price = Order_price_coupon_15$order_price, group = 'Coupon_15'),
  data.frame(order_price = Order_price_coupon_25$order_price, group = 'Coupon_25'))
View(data_anova)
head(data_anova)
 5.2.3. Tạo các tập dữ liệu train.tokens.df, test.tokens.df và word_df từ   tập dữ liệu new_df 
#Xem phân phối biến is_happy_customer; 0: Khong hai long va 1: Hai long
prop.table(table(new_df$is_happy_customer))
## 
##     0     1 
## 0.282 0.718
set.seed(32)
indexe<-createDataPartition(new_df$is_happy_customer,times=1,p=0.85,list=FALSE)

#Tạo tập dữ liệu train chứa 85% số lượng quan trắc
train<-new_df[indexe,]
#Phân phối của 85% quan trắc này  xấp xỉ với phân phối của các quan trắc trong tập new_df
prop.table(table(train$is_happy_customer))
## 
##         0         1 
## 0.2816901 0.7183099
#Tạo tập dữ liệu test chứa 15% số lượng quan trắc 

test<-new_df[-indexe,]

#Phân phối của 15% quan trắc này phải xấp xỉ với phân phối  trong tap new_df

prop.table(table(test$is_happy_customer))
## 
##         0         1 
## 0.2837838 0.7162162
# Phương pháp tokenization
train.tokens<-tokens(train$latest_customer_review,what="word",
                     remove_numbers=TRUE,remove_punct=TRUE,remove_symbols=TRUE)
test.tokens<-tokens(test$latest_customer_review,what="word",
                    remove_numbers=TRUE,remove_punct=TRUE,remove_symbols=TRUE)

#Chỉnh các kí tự thành các kí tự thường
train.tokens<-tokens_tolower(train.tokens)
test.tokens<-tokens_tolower(test.tokens)

#Các từ đồng nghĩa sẽ được biểu diễn là 1 từ
train.tokens<-tokens_wordstem(train.tokens,language = "english")
test.tokens<-tokens_wordstem(test.tokens,language = "english")

#Loại bỏ các từ như: the; is; a;....
train.tokens<-(tokens_select(train.tokens,stopwords(),selection="remove"))
test.tokens<-(tokens_select(test.tokens,stopwords(),selection="remove"))

#Document feature matrix
train.tokens.dfm<-dfm(train.tokens,tolower=FALSE)
test.tokens.dfm<-dfm(test.tokens,tolower=FALSE)

train.tokens.matrix<-as.matrix(train.tokens.dfm)
test.tokens.matrix<-as.matrix(test.tokens.dfm)

train.tokens.df<-cbind(is_happy_customer=train$is_happy_customer,order_id=train$order_id,as.data.frame(train.tokens.dfm))
test.tokens.df<-cbind(is_happy_customer=test$is_happy_customer,order_id=test$order_id,as.data.frame(test.tokens.dfm))
names(train.tokens.df)<-make.names(names(train.tokens.df))
names(test.tokens.df)<-make.names(names(test.tokens.df))
View(train.tokens.df)
View(test.tokens.df)

head(train.tokens.df)
head(test.tokens.df)
# Thống kê số lần các từ xuất hiện trong tập train.tokens.df
freq<-colSums(train.tokens.matrix)
length(freq)
## [1] 1270
wf= data.frame(term=names(freq),occurrences=freq)
View(wf)
head(wf)
#Kiểm tra các từ xuất hiện hơn 60 lan trong tập dữ liệu train.tokens: "phone" "star"  "good"  "love"  "use"   "work"  "great"  "one" 
dtm<-DocumentTermMatrix(train.tokens)
findFreqTerms(dtm ,lowfreq = 60)
## [1] "phone" "star"  "good"  "one"   "love"  "use"   "work"  "great"
which( colnames(train.tokens.df)=="phone" )
## [1] 5
which( colnames(train.tokens.df)=="star" )
## [1] 23
which( colnames(train.tokens.df)=="good" )
## [1] 24
which( colnames(train.tokens.df)=="great" )
## [1] 123
which( colnames(train.tokens.df)=="love" )
## [1] 36
which( colnames(train.tokens.df)=="use" )
## [1] 48
which( colnames(train.tokens.df)=="work" )
## [1] 76
#Tao tap du lieu moi word_df
word_df<-train.tokens.df[c(1,2,5,23,24,123,36,48,76)]
View(word_df)
head(word_df)

V. Thống kê mô tả
1. Thống kê cho bài toán ANOVA 1 nhân tố

dim(Order_price_coupon_0)
## [1] 104   2
summary(Order_price_coupon_0)
##   order_price    coupon_discount
##  Min.   : 1010   Min.   :0      
##  1st Qu.: 7612   1st Qu.:0      
##  Median :13372   Median :0      
##  Mean   :14067   Mean   :0      
##  3rd Qu.:19833   3rd Qu.:0      
##  Max.   :37570   Max.   :0
dim(Order_price_coupon_5)
## [1] 101   2
summary(Order_price_coupon_5)
##   order_price    coupon_discount
##  Min.   : 1660   Min.   :5      
##  1st Qu.: 6750   1st Qu.:5      
##  Median :11175   Median :5      
##  Mean   :13356   Mean   :5      
##  3rd Qu.:17660   3rd Qu.:5      
##  Max.   :31750   Max.   :5
dim(Order_price_coupon_10)
## [1] 95  2
summary(Order_price_coupon_10)
##   order_price    coupon_discount
##  Min.   :  730   Min.   :10     
##  1st Qu.: 7785   1st Qu.:10     
##  Median :12810   Median :10     
##  Mean   :14031   Mean   :10     
##  3rd Qu.:19615   3rd Qu.:10     
##  Max.   :35205   Max.   :10
dim(Order_price_coupon_15)
## [1] 101   2
summary(Order_price_coupon_15)
##   order_price    coupon_discount
##  Min.   : 1010   Min.   :15     
##  1st Qu.: 7535   1st Qu.:15     
##  Median :13595   Median :15     
##  Mean   :14424   Mean   :15     
##  3rd Qu.:21350   3rd Qu.:15     
##  Max.   :35180   Max.   :15
dim(Order_price_coupon_25)
## [1] 99  2
summary(Order_price_coupon_25)
##   order_price    coupon_discount
##  Min.   :  585   Min.   :25     
##  1st Qu.: 6685   1st Qu.:25     
##  Median :12350   Median :25     
##  Mean   :13641   Mean   :25     
##  3rd Qu.:20360   3rd Qu.:25     
##  Max.   :33440   Max.   :25

Vẽ biểu đồ cột với màu sắc cho từng nhóm coupon discount

ggplot(data_anova, aes(x = group, y = order_price, fill = group)) +
  geom_col() 

Vẽ biểu đồ histogram cho biến order_price ở từng nhóm coupon

hist(Order_price_coupon_0$order_price, col = "lightblue", main = "Biểu đồ Histogram của biến order_price theo nhóm coupon 0")

hist(Order_price_coupon_5$order_price, col = "lightblue", main = "Biểu đồ Histogram của biến order_price theo nhóm coupon 5")

hist(Order_price_coupon_10$order_price, col = "lightblue", main = "Biểu đồ Histogram của biến order_price theo nhóm coupon 10")

hist(Order_price_coupon_15$order_price, col = "lightblue", main = "Biểu đồ Histogram của biến order_price theo nhóm coupon 15")

hist(Order_price_coupon_25$order_price, col = "lightblue", main = "Biểu đồ Histogram của biến order_price theo nhóm coupon 25")

Biểu đồ boxplot of order_price cho từng nhóm coupon discount

ggplot(data_anova,aes(x=group,y=order_price,fill=group))+geom_boxplot() 

2. Thống kê mô tả cho bài toán hồi quy

#Biểu đồ phần trăm độ hài lòng của khách hàng trong tập word_df
PieChart(is_happy_customer, hole = 0, values = "%", data = word_df,
         fill = c("red", "green"), main = "")

## >>> suggestions
## PieChart(is_happy_customer, hole=0)  # traditional pie chart
## PieChart(is_happy_customer, values="%")  # display %'s on the chart
## PieChart(is_happy_customer)  # bar chart
## Plot(is_happy_customer)  # bubble plot
## Plot(is_happy_customer, values="count")  # lollipop plot 
## 
## --- is_happy_customer --- 
## 
##                    0      1     Total 
## Frequencies:     120    306       426 
## Proportions:   0.282  0.718     1.000 
## 
## Chi-squared test of null hypothesis of equal probabilities 
##   Chisq = 81.211, df = 1, p-value = 0.000

Biểu đồ histogram cho các từ xuất hiện nhiều hơn 60 lần trong tập word_df

p<-ggplot(subset(wf,freq>59),aes(term,occurrences))+geom_bar(stat="identity")
p

wordcloud

set.seed(32)

wordcloud(names(freq),freq,min.freq=60,colors=brewer.pal(11,"Dark2"))

  1. Thong ke suy dien
  1. Bài toán ANOVA để kiểm chứng liệu có sự khác biệt giữa trung bình giữa giá các đơn hàng theo từng nhóm % giảm giá hay không
    1.1. Mô hình ANOVA
anova_result <- aov(order_price ~ group, data = data_anova)
# In kết quả ANOVA
summary(anova_result)
##              Df      Sum Sq  Mean Sq F value Pr(>F)
## group         4    68672394 17168098   0.255  0.907
## Residuals   495 33363475317 67400960

1.2. Kiểm định giả thiết của mô hình 1.2.1. kiểm định từng mẫu có thỏa phân phối chuẩn hay không ?

shapiro.test(Order_price_coupon_0$order_price)
## 
##  Shapiro-Wilk normality test
## 
## data:  Order_price_coupon_0$order_price
## W = 0.95989, p-value = 0.00312
shapiro.test(Order_price_coupon_5$order_price)
## 
##  Shapiro-Wilk normality test
## 
## data:  Order_price_coupon_5$order_price
## W = 0.935, p-value = 0.00008921
shapiro.test(Order_price_coupon_10$order_price)
## 
##  Shapiro-Wilk normality test
## 
## data:  Order_price_coupon_10$order_price
## W = 0.96248, p-value = 0.008042
shapiro.test(Order_price_coupon_15$order_price)
## 
##  Shapiro-Wilk normality test
## 
## data:  Order_price_coupon_15$order_price
## W = 0.95974, p-value = 0.003631
shapiro.test(Order_price_coupon_25$order_price)
## 
##  Shapiro-Wilk normality test
## 
## data:  Order_price_coupon_25$order_price
## W = 0.94352, p-value = 0.0003432
1.2.2.  Kiểm định phương sai giữa các nhóm coupon_discount theo biến order_price có bằng nhau không ? 
leveneTest(order_price ~ group, data = data_anova)
1.2.3.  Kiểm tra tính độc lập : 
dw_test <- durbinWatsonTest(anova_result)

print(dw_test)
##  lag Autocorrelation D-W Statistic p-value
##    1     -0.05774046      2.113262   0.248
##  Alternative hypothesis: rho != 0
  1. Bài toán dự đoán sự hài lòng của khách hàng qua phân tích bằng phương pháp NLP và dùng mô hình logistic
2.1. Mô hình logistic
# Mo hinh 1
logistic_model<-glm(is_happy_customer~phone+star+great+good+love+work+use  ,
                    data = word_df,
                    family = "binomial")
summary(logistic_model)
## 
## Call:
## glm(formula = is_happy_customer ~ phone + star + great + good + 
##     love + work + use, family = "binomial", data = word_df)
## 
## Coefficients:
##             Estimate Std. Error z value    Pr(>|z|)    
## (Intercept)  0.36420    0.20547   1.773    0.076309 .  
## phone       -0.24179    0.11800  -2.049    0.040455 *  
## star        -0.04680    0.31650  -0.148    0.882443    
## great        2.16001    0.42680   5.061 0.000000417 ***
## good         1.43062    0.36902   3.877    0.000106 ***
## love         2.94600    0.72669   4.054 0.000050356 ***
## work        -0.41864    0.23765  -1.762    0.078144 .  
## use          0.01676    0.26510   0.063    0.949587    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 506.55  on 425  degrees of freedom
## Residual deviance: 382.31  on 418  degrees of freedom
## AIC: 398.31
## 
## Number of Fisher Scoring iterations: 6
#Mo hinh 2
logistic_model1<-glm(is_happy_customer~phone+great+good+love,
                     data = word_df,
                     family = "binomial")
summary(logistic_model1)
## 
## Call:
## glm(formula = is_happy_customer ~ phone + great + good + love, 
##     family = "binomial", data = word_df)
## 
## Coefficients:
##             Estimate Std. Error z value    Pr(>|z|)    
## (Intercept)   0.2654     0.1665   1.593       0.111    
## phone        -0.2476     0.1148  -2.158       0.031 *  
## great         2.1169     0.4227   5.008 0.000000549 ***
## good          1.4400     0.3659   3.935 0.000083099 ***
## love          2.9789     0.7270   4.098 0.000041718 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 506.55  on 425  degrees of freedom
## Residual deviance: 385.60  on 421  degrees of freedom
## AIC: 395.6
## 
## Number of Fisher Scoring iterations: 6

Các khoảng ước lượng cho các hệ số đường hồi quy

#Khoảng ước lượng cho các hệ số đường hồi quy
 confint(logistic_model1)
## Waiting for profiling to be done...
##                   2.5 %      97.5 %
## (Intercept) -0.05997825  0.59408423
## phone       -0.47675926 -0.02490265
## great        1.38279292  3.06482069
## good         0.80554843  2.26632648
## love         1.79696817  4.79787895
 # Khoảng ước lượng cho tỉ lệ khả năng
exp(cbind(Odds_Ratio = coef(logistic_model1), confint(logistic_model1)))
## Waiting for profiling to be done...
##             Odds_Ratio    2.5 %      97.5 %
## (Intercept)  1.3039116 0.941785   1.8113714
## phone        0.7806474 0.620792   0.9754049
## great        8.3050777 3.986019  21.4306190
## good         4.2208323 2.237924   9.6439086
## love        19.6656637 6.031334 121.2529609
2.3. Dự đoán sự hài lòng của khách hàng trong tập dữ liệu test.tokens.df
probabilities <- (predict(logistic_model1, 
                          newdata = test.tokens.df,
                          type = "response"))
Predictions <-(ifelse(probabilities > 0.5, 1, 0))

Confusion matrix

#confusion matrix
table(Predictions,test.tokens.df$is_happy_customer)
##            
## Predictions  0  1
##           0  4  6
##           1 17 47
#Precision
(47)/(47+6)
## [1] 0.8867925
2.4. Hosmer lemeshow test để kiểm tra tính chính xác của mô hình 
hl<- hoslem.test(word_df$is_happy_customer,fitted(logistic_model),g=10)
hl
## 
##  Hosmer and Lemeshow goodness of fit (GOF) test
## 
## data:  word_df$is_happy_customer, fitted(logistic_model)
## X-squared = 426, df = 8, p-value < 0.00000000000000022
2.5. Kiểm tra các giả thiết của mô hình 2:

 2.5.1. kiểm tra giả thiết:  Không có hiện tượng cộng đa tuyến ( multicollinearity)
vif(logistic_model1)
##    phone    great     good     love 
## 1.004899 1.007141 1.005384 1.000903
 2.5.2. Có sự phụ thuộc tuyến tính của các biến độc lập vào giá trị  logarit xác suất
probabilities1 <- (predict(logistic_model1, 
                    data = word_df,
                          type = "response"))
logit=log(probabilities1/(1-probabilities1))


ggplot(word_df, aes(logit, good))+
  geom_point(size = 0.5, alpha = 0.5) +
  geom_smooth(method = "loess")
## `geom_smooth()` using formula = 'y ~ x'

ggplot(word_df, aes(logit, great))+
  geom_point(size = 0.5, alpha = 0.5) +
  geom_smooth(method = "loess") 
## `geom_smooth()` using formula = 'y ~ x'

ggplot(word_df, aes(logit, love))+
  geom_point(size = 0.5, alpha = 0.5) +
  geom_smooth(method = "loess")
## `geom_smooth()` using formula = 'y ~ x'

2.5.3. Ta tìm các điểm ảnh hưởng mạnh là các outliers

plot(cooks.distance(logistic_model1),type="b")