bd=read.csv("https://archive.ics.uci.edu/ml/machine-learning-databases/balance-scale/balance-scale.data")
> head(bd)
B X1 X1.1 X1.2 X1.3
1 R 1 1 1 2
2 R 1 1 1 3
3 R 1 1 1 4
4 R 1 1 1 5
5 R 1 1 2 1
6 R 1 1 2 2
天秤の傾き/釣り合いの判定。
Bが目的変数で、釣り合い・左・右のどれかになります。
他は距離と質量。知識があれば2列目*3列目がモーメントになるので、その特徴量で判定すればOK。
試しにそのままでランダムフォレストでやってみると
tuneRF(y=bd[,1],x=bd[,-1],doBest = T)
Confusion matrix:
B L R class.error
B 0 6 33 1.00000000
L 0 187 14 0.06965174
R 0 3 257 0.01153846
B(釣り合い)が全然識別出来てないです。
4つの特徴量から2つずつ選び、4C2=6種類の交互作用項を追加します。
cbs=combn(c(2:5),2)
nfuture=data.frame(matrix(0,nrow=nrow(bd))) #新しい特徴量
for(j in 1:ncol(cbs)){
f1=cbs[1,j]
f2=cbs[2,j]
nfuture[[paste("f",f1,f2,sep="")]]=bd[,f1]*bd[,f2]
}
nfuture=nfuture[,-1]
ndf=cbind(bd,nfuture)
trow=sample(500,100)
test=ndf[trow,]
ndf=ndf[-trow,]
tuneRF(y=ndf[,1],x=ndf[,-1],doBest = T)
rf=randomForest(B~.,ndf)
p.rf=predict(rf,newdata=test)
table(test[,1],p.rf)
# p.rf
# B L R
# B 7 1 4
# L 3 38 1
# R 1 0 45
少しはマシに・・・。
で、特徴量削除すべきなので、本命の多項Logit&Lasso回帰。alpha=1がLassoの指定です。
gnet.cvlasso=cv.glmnet(x=as.matrix(ndf[,-1]),y=ndf[,1],family="multinomial",alpha=1,type.measure="class")
table(test[,1],prd)
B L R
B 12 0 0
L 0 42 0
R 0 0 46
'''