線形サポートベクターマシン

Rで学ぶSupport Vector Machines

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で学ぶSupport Vector Machines

決定境界とカーネル

  • 決定境界は直線、多項式、より複雑な関数など、さまざまな形状をとります。
  • 決定境界の種類はカーネルと呼ばれます。
  • カーネルは事前に指定する必要があります。
  • この章では線形カーネルに焦点を当てます。
Rで学ぶSupport Vector Machines

線形カーネルによるSVM

  • e1071 ライブラリの svm 関数を使用します。
  • この関数にはいくつかのパラメーターがあります。以下を明示的に設定します:
    • formula - 目的変数を指定する式。ここでは y です。
    • data - データを含むデータフレーム(trainset)。
    • type - C-classification(分類問題)に設定。
    • kernel - 決定境界の形式。ここでは linear。
    • costgamma - モデルのチューニングに使用するパラメーター。
    • scale - データをスケーリングするかを示す論理値。
Rで学ぶSupport Vector Machines

線形SVMの構築

  • e1071 ライブラリを読み込み、svm() 関数を呼び出します
library(e1071)
svm_model<- svm(y ~ .,
                data = trainset, 
                type = "C-classification", 
                kernel = "linear", 
                scale = FALSE)
Rで学ぶSupport Vector Machines

モデルの概要

  • svm_model を入力すると以下が表示されます:
    • 分類・カーネルの種類を含むモデルの概要
    • チューニングパラメーターの値
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で学ぶSupport Vector Machines
# 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で学ぶSupport Vector Machines
  • 訓練セットとテストセットのクラス予測を取得します。
  • モデルの訓練・テスト精度を評価します。
# 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で学ぶSupport Vector Machines

練習しましょう!

Rで学ぶSupport Vector Machines

Preparing Video For Download...