心臓病UCIデータセットのRでKmeansアルゴリズムを実行しています。データセットのように、それぞれ138165サイズの2つのクラスターを取得することになっています。
手順:
df <- read.csv(".../heart.csv",fileEncoding = "UTF-8-BOM")
features = subset(df, select = -target)
normalize <- function(x) {
return ((x - min(x)) / (max(x) - min(x)))
}
features = data.frame(sapply(features, normalize))
set.seed(0)
cluster = kmeans(features, 2)
cluster$size
出力:
[1] 99 204
どうして?
予測の精度ではなく、クラスターのサイズに焦点を当てているようです。サイズ(138、165)の2つのクラスターを取得することもできますが、データの「ターゲット」列と同じクラスターである必要はありません。
パフォーマンスを判断するためのより良い方法は、予測の正確さです。あなたの場合、モデルの精度は72%です。あなたはこれを見ることができます:
df$label <- cluster$cluster -1
confusionMatrix(table(df$target, df$label))
#Confusion Matrix and Statistics
#
# 0 1
# 0 76 62
# 1 23 142
#
# Accuracy : 0.7195
# ...
正規化するのではなく、データを標準化することで、より高い精度を得ることができました。おそらく、標準化が外れ値に対してより堅牢であるためです。
また、精度が向上したと思われるカテゴリ別の変数をダミーコード化しました。現在、85%の精度があり、クラスターサイズは予想(143 160)に近づいています。ただし、説明したように、それ自体ではクラスターサイズは無意味です。
library(dplyr)
library(fastDummies)
library(caret)
standardize <- function(x){
num <- x - mean(x, na.rm=T)
denom <- sd(x, na.rm=T)
num/denom
}
# dummy-code and standardize
features <- select(df, -target) %>%
dummy_cols(select_columns = c('cp','thal', 'ca'),
remove_selected_columns = T,remove_first_dummy = T) %>%
mutate_all(standardize)
set.seed(0)
cluster <- kmeans(features, centers = 2, nstart = 50)
cluster$size
# 143 160
# check predictions vs actual labels
df$label <- cluster$cluster -1
confusionMatrix(table(df$target, df$label))
#Confusion Matrix and Statistics
#
#
# 0 1
# 0 117 21
# 1 26 139
#
# Accuracy : 0.8449
もちろん、サンプル外の精度(データをトレーニングセットとテストセットに分割し、テストセットの予測の精度を計算する)やf1スコアなど、考慮する価値のある他の精度メトリックもあります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加