1. Cài đặt các gói cần thiết nếu chưa có

library(dbscan)
## 
## Attaching package: 'dbscan'
## The following object is masked from 'package:stats':
## 
##     as.dendrogram
library(solitude)

2. Tạo một bộ dữ liệu

set.seed(123)
data <- rnorm(100, mean = 50, sd = 10)
data <- c(data, 200, 210, 190) # Thêm vài điểm ngoại lai

3. Boxplot

boxplot(data, main="Boxplot để xác định outliers")

4. Z-score

z_scores <- scale(data)
outliers_zscore <- data[abs(z_scores) > 3]
print("Outliers (Z-score):")
## [1] "Outliers (Z-score):"
print(outliers_zscore)
## [1] 200 210 190

5. Distance-based methods (KNN)

data_matrix <- matrix(data, ncol = 1)
kNNdistplot(data_matrix, k = 2)
abline(h = 20, col = "red") # Giả sử ngưỡng là 20

6. Isolation Forest

data_frame <- data.frame(value = data)
sample_size <- min(256, nrow(data_frame))  # Sử dụng kích thước mẫu nhỏ hơn hoặc bằng số lượng hàng
model <- solitude::isolationForest$new(sample_size = sample_size)
model$fit(data_frame)
## INFO  [10:58:11.074] Building Isolation Forest ...
## INFO  [10:58:11.450] done
## INFO  [10:58:11.453] Computing depth of terminal nodes ...
## INFO  [10:58:11.610] done
## INFO  [10:58:11.616] Completed growing isolation forest
scores <- model$predict(data_frame)
threshold <- 0.6
outliers_isolation <- data_frame[scores$anomaly_score > threshold, ]
cat("Outliers (Isolation Forest):\n")
## Outliers (Isolation Forest):
print(outliers_isolation)
##  [1]  30.33383  33.13307  71.68956  34.51247  70.50085  26.90831  71.87333
##  [8] 200.00000 210.00000 190.00000

7. Scatter Plot

y <- rnorm(100, mean = 50, sd = 10)
y <- c(y, 200, 210, 190) # Thêm vài điểm ngoại lai vào y
# Tính Z-score cho cả data và y
z_scores <- scale(data)
z_scores_y <- scale(y)

8. Vẽ scatter plot

plot(data, y, main = "Scatter Plot để xác định outliers", xlab = "X", ylab = "Y", pch = 19, col = "blue")

9. Đánh dấu các điểm ngoại lai (giả sử dùng Z-score để xác định)

# Đánh dấu các điểm ngoại lai trên scatter plot
# Scatter Plot
y <- rnorm(100, mean = 50, sd = 10)
y <- c(y, 200, 210, 190) # Thêm vài điểm ngoại lai vào y

# Tính Z-score cho cả data và y
z_scores <- scale(data)
z_scores_y <- scale(y)

# Vẽ scatter plot
plot(data, y, main = "Scatter Plot để xác định outliers", xlab = "X", ylab = "Y", pch = 19, col = "blue")

# Đánh dấu các điểm ngoại lai trên scatter plot
outliers_scatter <- which(abs(z_scores) > 3 | abs(z_scores_y) > 3)
points(data[outliers_scatter], y[outliers_scatter], col = "red", pch = 19)

# Thêm chú thích
legend("bottomright", legend = c("Normal points", "Outliers"), col = c("blue", "red"), pch = 19)