線性支援向量機

R 的支援向量機

Kailash Awati

Instructor

切分訓練集與測試集

  • 先前章節產生的資料集在資料框 df 中。
  • 將資料集切成訓練集與測試集
  • 隨機 80/20 切分
    # Set seed for reproducibility
    set.seed(1)
    # Set the upper bound for the number of rows to be in the training set
    sample_size <- floor(0.8 * nrow(df))
    # Assign rows to training/test sets randomly in 80/20 proportion
    train <- sample(seq_len(nrow(df)), size = sample_size)
    # Separate training and test sets
    trainset <- df[train, ]
    testset <- df[-train, ]
    
R 的支援向量機

決策邊界與 kernel

  • 決策邊界可呈現不同形狀:直線、多項式或更複雜的函式。
  • 決策邊界的型式稱為 kernel
  • 必須事先指定 kernel。
  • 本章聚焦於線性 kernel。
R 的支援向量機

線性 kernel 的 SVM

  • 我們將使用 e1071 函式庫的 svm 函式。
  • 此函式有多個參數。我們會明確設定以下項目:
    • formula-指定應變數的公式,本例為 y。
    • data-包含資料的資料框,即 trainset。
    • type-設為 C-classification(分類問題)。
    • kernel-決策邊界的形式,本例為 linear。
    • costgamma-用來調整模型的參數。
    • scale-布林值,是否要縮放資料。
R 的支援向量機

建立線性 SVM

  • 載入 e1071 函式庫並呼叫 svm() 函式
library(e1071)
svm_model<- svm(y ~ .,
                data = trainset, 
                type = "C-classification", 
                kernel = "linear", 
                scale = FALSE)
R 的支援向量機

模型總覽

  • 輸入 svm_model 會顯示:
    • 模型總覽(包含分類與 kernel 類型)
    • 調參數值
svm_model
Call:
svm(formula = y ~ .,
    data = trainset,
    type = "C-classification",
    kernel = "linear", 
    scale = FALSE)

Parameters:
   SVM-Type:  C-classification 
 SVM-Kernel:  linear 
       cost:  1 
      gamma:  0.5

Number of Support Vectors: 55
R 的支援向量機
# Index of support vectors in training dataset
svm_model$index

# Support vectors svm_model$SV
# Negative intercept (unweighted) svm_model$rho
# Weighting coefficients for support vectors svm_model$coefs
4   8  10  11  18  37  38  39  47  59  60  74  76  77  78  80  83 ...

x1 x2 5 0.519095949 0.44232464
-0.1087075
[,1] [1,] 1.0000000
R 的支援向量機
  • 取得訓練集與測試集的類別預測。
  • 評估模型在訓練集與測試集的準確率。
# Training accuracy
pred_train <- predict(svm_model, trainset)
mean(pred_train == trainset$y)
1
# Test accuracy
pred_test <- predict(svm_model, testset)
mean(pred_test == testset$y)
1
# Perfect!!
R 的支援向量機

一起來練習吧!

R 的支援向量機

Preparing Video For Download...