A: BIEN LIEN TUC

I: PHAN PHOI DEU UNIFORM- Hinh chu nhat, doan du lieu #Một biến ngẫu nhiên tuân theo phân phối đều trên đoạn [5,15] . Tính xác suất trong khoảng từ 7 đến 12

#1: punif:  xac suat tich luy(x<=X voi xac suat bao nhieu)
#tinh tay: 
x<-(12-7)/(15-5)
x
## [1] 0.5
#tinh bang punif: ham phan phoi xac suat tich luy
punif (12, min = 5, max = 15) - punif(7, min = 5, max = 15)
## [1] 0.5
#punif (12, min = 5, max = 15) = (12-5)/(15-5)
#punif(7, min = 5, max = 15) = (7-5)(15-5)

punif(6, min = 2, max = 8) - punif(3, min = 2, max = 8)
## [1] 0.5
#2: dunif: mat do xac suat( ko phai xac suat, la chieu cao do thi)
#chieu cao tai x=7: 
dunif(7, min = 5, max = 15)     #f(x)=1/(b-a)=1/15-5
## [1] 0.1
#3: qunif: tim gia tri theo xac suat
#50% xac suat la gia tri nao
qunif(0.5, min = 5, max = 15) #=a+p*(b-a)=5+0.5*(15-5)
## [1] 10
#4: runif: sinh so ngau nhien
#ko trung lap: dung set.seed(1)
set.seed(1)
x<-runif(5, min = 5, max = 15)
y<-unique(x)
y
## [1]  7.655087  8.721239 10.728534 14.082078  7.016819

II: PHAN PHOI CHUAN NORMAL - chieu cao, diem so #Chiều cao của sinh viên một trường đại học tuân theo phân phối chuẩn với trung bình 170 cm và độ lệch chuẩn 5 cm.

#1: pnorm - xac suat tich luy (x<=X voi xac suat bao nhieu)*
pnorm(175, 170, 5) 
## [1] 0.8413447
f <- function(t){
  (1/(5*sqrt(2*pi))) * exp(-(t-170)^2/(2*5^2))
}
p<- integrate(f, -Inf, 175)$value
p
## [1] 0.8413447
1-pnorm(175, 170, 5) #chieu cao >175
## [1] 0.1586553
#xac suat trong khoang 165-175
pnorm(175, 170, 5)-pnorm(165, 170, 5)
## [1] 0.6826895
#2: dnorm - mat do
dnorm(175, 170, 5)    #(1/(sigma*sqrt(2*pi))) * exp(-(x-tb)^2/(2*sigma^2))
## [1] 0.04839414
#(1/(5*sqrt(2*pi))) * exp(-(175-170)^2/(2*5^2))


#3: qnorm - tim gia tri theo xac suat
qnorm(0.4, 170, 5)
## [1] 168.7333
#4: rnorm - sinh du lieu
rnorm(11, 170, 5)
##  [1] 176.3621 172.0732 162.3002 165.3572 168.5264 169.9712 182.0233 173.8180
##  [9] 166.0050 164.2617 168.5527

III: PHAN PHOI MU EXP - thoi gian cho giua cac su kien #Thời gian giữa hai lần khách hàng vào quán cà phê tuân theo phân phối mũ với trung bình 5 phút (mean=5 => rate=lambda=1/mean=1/5)

#1: pexp - xac suat (exp: tg cho)
pexp(3, 1/5)        #tg cho <= 3p =1-exp(-lambda*x)=1-exp(-1/5*3)
## [1] 0.4511884
1-pexp(3, 1/5)      #tg cho >=3p   
## [1] 0.5488116
#2: dexp - mat do
dexp(3, 1/5)        #mat do tg cho <=3  lambda*exp(-lambda*x)=1/5*exp(-1/5*3)
## [1] 0.1097623
#3: qexp - tim gia tri dua tren xac suat
qexp(0.45, 1/5)     #gia tri co xac suat 45% la =(-1/lambda)*log(1-p)=(-1/(1/5)*log(1-0.45)
## [1] 2.989185
#4: rexp - sinh du lieu
rexp(11, 1/5)
##  [1]  6.1134950  1.1795597  0.9956583  4.1111169  2.9423986 11.8225763
##  [7]  3.2094629  1.4706019  2.8293276  0.5303631  0.2971958

A: BIEN ROI RAC I: PHAN PHOI POISSON - dem so su kien (cuoc goi, so khach hang, so loi, tb lambda) #Số cuộc gọi đến trong một phút tuân theo phân phối Poisson với λ = 3, xac suat co dung 5 cuoc goi

#1: ppois - xac suat <=
ppois(3, lambda = 3)           #xac suat <=3   
## [1] 0.6472319
#for(i in 0:k){exp(-lambda) * lambda^i / factorial(i)}
#p<-0
#for(i in 0:3){
#  p<-p+exp(-3) * 3^i / factorial(i)
#}
#p
1- ppois(2, lambda = 3)       #xac suat >=x: 1- ppois(x-1, lambda)
## [1] 0.5768099
# Tính xác suất có ít nhất 3 khách hàng đến trong một phút với λ = 2.
 1-ppois(2, lambda = 2)
## [1] 0.3233236
#2: dpois - xac suat dung =
dpois(5, lambda = 3)        #exp(-lambda) * lambda^k / factorial(k)
## [1] 0.1008188
#exp(-3)*3^5/factorial(5)

#3: qpois: tim gia tri
qpois(0.5, lambda = 3)
## [1] 3
#4: rpois: sinh du lieu
rpois(10, lambda = 3)
##  [1] 4 0 3 4 4 3 5 3 2 1

II: PHAN PHOI NHI THUC BINOMIAL (xac suat thanh cong / that bai sau n lan lap) #Một nhà máy có xác suất sản phẩm lỗi là 𝑝=0.1, Kiểm tra 10 sản phẩm.

#1: pbinom - xac suat <=
pbinom(3, 10, 0.1)      #Xác suất có nhiều nhất 3 sản phẩm lỗi
## [1] 0.9872048
1-pbinom(3, 10, 0.1)    #Xác suất có it nhất 3 sản phẩm lỗi
## [1] 0.0127952
#2: dbinom - xac suat dung =
dbinom(2, 10, 0.1)      #Xác suất có đúng 2 sản phẩm lỗi
## [1] 0.1937102
#3: qbinom - tim gia tri dua tren xac suat
qbinom(0.23, 10, 0.1)     
## [1] 0
#4: rbinom - sinh du lieu
rbinom(4, 10, 0.1)
## [1] 0 0 1 1

C: BO DU LIEU BOSTON

library(MASS)
myd<-(Boston)
model<-lm(medv~nox+tax+rm, data = myd)
summary(model)
## 
## Call:
## lm(formula = medv ~ nox + tax + rm, data = myd)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -15.784  -3.219  -0.782   2.412  41.616 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -17.658150   3.235967  -5.457 7.63e-08 ***
## nox          -7.176586   3.175910  -2.260   0.0243 *  
## tax          -0.012709   0.002176  -5.840 9.41e-09 ***
## rm            7.854108   0.407533  19.272  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.084 on 502 degrees of freedom
## Multiple R-squared:  0.565,  Adjusted R-squared:  0.5624 
## F-statistic: 217.3 on 3 and 502 DF,  p-value: < 2.2e-16
coef(model)
##  (Intercept)          nox          tax           rm 
## -17.65815000  -7.17658571  -0.01270934   7.85410819
#Kiem tra da cong tuyen vif
library(car)
## Warning: package 'car' was built under R version 4.5.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.5.3
vif(model)    #=1->ko co, >5:co, >10: da cong tuyen manh
##      nox      tax       rm 
## 1.847723 1.835551 1.118573
#stepAIC chon cac bien quan trong
model_step <- stepAIC(model, direction = "both")
## Start:  AIC=1831.33
## medv ~ nox + tax + rm
## 
##        Df Sum of Sq   RSS    AIC
## <none>              18582 1831.3
## - nox   1     189.0 18771 1834.5
## - tax   1    1262.3 19844 1862.6
## - rm    1   13748.6 32331 2109.6
summary(model_step)
## 
## Call:
## lm(formula = medv ~ nox + tax + rm, data = myd)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -15.784  -3.219  -0.782   2.412  41.616 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -17.658150   3.235967  -5.457 7.63e-08 ***
## nox          -7.176586   3.175910  -2.260   0.0243 *  
## tax          -0.012709   0.002176  -5.840 9.41e-09 ***
## rm            7.854108   0.407533  19.272  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.084 on 502 degrees of freedom
## Multiple R-squared:  0.565,  Adjusted R-squared:  0.5624 
## F-statistic: 217.3 on 3 and 502 DF,  p-value: < 2.2e-16
#so sanh 2 mo hinh bang MSE
mse1 <- mean(model$residuals^2)
mse2 <- mean(model_step$residuals^2)  #trung binh sai so binh phuong
mse1
## [1] 36.72346
mse2
## [1] 36.72346
#do thi residual vs fitted
plot(model$fitted.values, resid(model),
     col = "lightseagreen",
     pch = 16,
     cex = 0.5,
     xlab = "Fitted values",
     ylab = "Residuals",
     main = "Residuals vs Fitted")

abline(h = 0, col = "red")

axis(1, at = seq(0, 50, by = 10))

BO DU LIEU IRIS

#su dung bo du lieu iris
md<-(iris)
head(md)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
#loc ko lay virsinica, chuyen ten loai thanh vecto 0, 1
loc<-subset(md, Species!="virginica")   #loc<-md[md$Species!="virsinica", ]

#ma hoa nhan
loc$Species<-ifelse(loc$Species=="versicolor", 1, 0)

#mo hinh hoi quy ligistic
model<-glm(Species~Sepal.Length+Petal.Length+Petal.Width, data = loc, family = binomial)
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(model)
## 
## Call:
## glm(formula = Species ~ Sepal.Length + Petal.Length + Petal.Width, 
##     family = binomial, data = loc)
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)
## (Intercept)       5.213 575458.883       0        1
## Sepal.Length    -16.539 132345.998       0        1
## Petal.Length     23.860  76702.645       0        1
## Petal.Width      27.591 136533.255       0        1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1.3863e+02  on 99  degrees of freedom
## Residual deviance: 1.4971e-09  on 96  degrees of freedom
## AIC: 8
## 
## Number of Fisher Scoring iterations: 25
#ma tran nnham lan
# Xác suất dự đoán
prob <- predict(model, type = "response")

# Phân lớp với ngưỡng 0.5
pred <- ifelse(prob > 0.5, 1, 0)
x<-table(Predicted = pred, Actual = loc$Species)
x
##          Actual
## Predicted  0  1
##         0 50  0
##         1  0 50
#do chinh xac cua mo hinh
accuracy <- mean(pred == loc$Species)
accuracy
## [1] 1
TP <- x["1","1"]
TN <- x["0","0"]
FP <- x["1","0"]
FN <- x["0","1"]
# Accuracy
accuracy <- (TP + TN) / sum(x)

# Precision
precision <- TP / (TP + FP)

# Recall
recall <- TP / (TP + FN)

# F1-score
f1 <- 2 * precision * recall / (precision + recall)

accuracy
## [1] 1
precision
## [1] 1
recall
## [1] 1
f1 
## [1] 1
#petal.length
# Tạo dải giá trị
x_seq <- seq(min(loc$Petal.Length), max(loc$Petal.Length), length=100)

# Giữ các biến khác cố định (lấy trung bình)
new_data <- data.frame(
  Sepal.Length = mean(loc$Sepal.Length),
  Petal.Length = x_seq,
  Petal.Width  = mean(loc$Petal.Width)
)

# Dự đoán xác suất
prob_curve <- predict(model, newdata = new_data, type = "response")

# Vẽ đồ thị
plot(x_seq, prob_curve, type="l", lwd=2,
     xlab="Petal.Length", ylab="Probability",
     main="Đường cong Sigmoid")

abline(h=0.5, col="red", lty=2)  # ngưỡng 0.5

#petal.width
x_seq <- seq(min(loc$Petal.Width), max(loc$Petal.Width), length=100)

new_data <- data.frame(
  Sepal.Length = mean(loc$Sepal.Length),
  Petal.Length = mean(loc$Petal.Length),
  Petal.Width  = x_seq
)

prob_curve <- predict(model, newdata = new_data, type = "response")

plot(x_seq, prob_curve, type="l", lwd=2,
     xlab="Petal.Width", ylab="Probability",
     main="Sigmoid theo Petal.Width")

abline(h=0.5, col="red", lty=2)

#sepal.length
x_seq <- seq(min(loc$Sepal.Length), max(loc$Sepal.Length), length=100)

new_data <- data.frame(
  Sepal.Length = x_seq,
  Petal.Length = mean(loc$Petal.Length),
  Petal.Width  = mean(loc$Petal.Width)
)

prob_curve <- predict(model, newdata = new_data, type = "response")

plot(x_seq, prob_curve, type="l", lwd=2,
     xlab="Sepal.Length", ylab="Probability",
     main="Sigmoid theo Sepal.Length")

abline(h=0.5, col="red", lty=2)

#kiem dinh hosmer-lemeshow
library(ResourceSelection)
## Warning: package 'ResourceSelection' was built under R version 4.5.3
## ResourceSelection 0.3-6   2023-06-27
hoslem.test(loc$Species, prob, g=10  )
## Warning in hoslem.test(loc$Species, prob, g = 10): The data did not allow for
## the requested number of bins.
## 
##  Hosmer and Lemeshow goodness of fit (GOF) test
## 
## data:  loc$Species, prob
## X-squared = 7.4857e-10, df = 1, p-value = 1