r - 如何修复 SVM 中的“不一致数组”错误?
问题描述
目前使用示例数据集练习 SVM,我正在尝试将 abline 添加到绘图中,但说 w[1,2] 不是正确的维度,导致我回到创建的变量“w”,其中“coefs”和“SV”不想在代码中工作
我试过小写 SV,它有效,但结果是 w | 数字(空)而不是 num [1, 1:2] -0.035 -0.0188。
structure(list(Height = c(44, 52.1, 57.1, 33, 27.8, 27.2, 32,
45.1, 56.7, 56.9, 122.1, 123.9, 122.9, 101.1, 128.9, 137.1, 127,
103, 141.6, 102.4), Weight = c(126.3, 136.9, 109.2, 148.3, 110.4,
107.8, 128.4, 120.2, 140.2, 139.2, 154.1, 170.8, 183.1, 164,
193.6, 181.7, 164.8, 174.6, 185.8, 176.9)), class = "data.frame", row.names = c(NA,
-20L))
#create an is horse indicator variable
ishorse <- c(rep(-1,10),rep(+1,10))
library(e1071)
#create data frame for performing svm
data <- data.frame(Height= animal_data['Height'],
Weight= animal_data['Weight'],
animal=as.factor(ishorse))
#plot data
plot(data[,-3],col=(3)/2, pch=19); abline(h=0,v=0,lty=3)
#perform svm
svm.model <- svm(animal ~ .,
data=data,
type='C-classification',
kernel='linear',
scale=FALSE)
#show support vectors
points(data[svm.model$index, c(1,2)], col="orange", cex = 2)
#get parameters of hyperplane
w <- t(svm.model$coefs) %% svm.model$SV
b <- -svm.model$rho
#in this 2D case the hyperplane is the line w[1,1]*x1 + w[1,2]*2 +b = 0
abline(a=-b/w[2,2], b=-w[,]/w[,], col = "blue", lty = 3)
解决方案
矩阵乘法的正确语法是%*%
. 试试这个:
svm.model <- svm(animal ~ .,
data=data,
type='C-classification',
kernel='linear',
scale=FALSE)
#show support vectors
points(data[svm.model$index, c(1,2)], col="orange", cex = 2)
#get parameters of hyperplane
w <- t(svm.model$coefs) %*% svm.model$SV
b <- -1*svm.model$rho
#in this 2D case the hyperplane is the line w[1,1]*x1 + w[1,2]*2 +b = 0
abline(a=-b/w[1,2], b=-w[1]/w[2], col = "blue", lty = 3)
推荐阅读
- mysql - 避免循环 - 递归 m2m 关系自引用
- rust - 如何使用 Serde 生成带有显示所有缺失值的占位符行的 TOML 文件?
- r - 检查/构建创建的 R 包时出错“LOGICAL() 只能应用于‘逻辑’,而不是‘整数’”
- javascript - 单击时,项目列表不会显示更多和更少的项目
- ruby-on-rails - 如果存在 JS,Capybara 找不到元素
- c# - UWP。当 AdaptiveGridView 的 ItemClickCommand 执行时如何传递命令参数?
- python - 如何使用 Python 打印 pandas 数据帧的单行?
- amazon-web-services - 如何使用 ingress-nginx 让 HTTP/2 在 Kubernetes 集群中工作
- java - Ecplise Java JNI, java.lang.UnsatisfiedLinkError loading dll
- java - 如何按列获取最后一个插入元素(不是“_id”列)