我是R的新手。我试图使用lda来分类生成的网格中的所有点。训练集是使用rmvnorm(n,mean,sigma)
随机生成的两个点组。这是我的代码:
# 样本数量n=100;# 参数:G2meanG1 = matrix( c(2, 2), # 数据元素 nrow=1, # 行数 ncol=2, # 列数 byrow = TRUE) # 按行填充矩阵 sigmaG1 = matrix( c(1,0,0,1), # 数据元素 nrow=2, # 行数 ncol=2, # 列数 byrow = TRUE) # 按行填充矩阵 library(mvtnorm) # 生成一个服从正态分布的矩阵G1 G1 = rmvnorm(n, meanG1, sigmaG1)G1[,3]=1# 参数:G2meanG2 = matrix( c(0, 0), # 数据元素 nrow=1, # 行数 ncol=2, # 列数 byrow = TRUE) # 按行填充矩阵 sigmaG2 = matrix( c(1,0.75,0.75,1), # 数据元素 nrow=2, # 行数 ncol=2, # 列数 byrow = TRUE) # 按行填充矩阵 # # 生成一个服从正态分布的矩阵G2G2 = rmvnorm(n, meanG2, sigmaG2)# 为G1矩阵添加一列作为标签 = 1 G1 = cbind(G1, 1 )# 为G2矩阵添加一列作为标签 = 2 G2 = cbind(G2, 2 ) # 连接两个矩阵G = rbind(G1,G2) # 将矩阵转换为数据框bothGroupsWithLabel <- as.data.frame(G)# 按行随机打乱数据bothGroupsWithLabel <- bothGroupsWithLabel[sample(nrow(bothGroupsWithLabel)),]# 绘制生成的矩阵plot(c(G1[,1]),c(G1[,2]),col="red")points(c(G2[,1]),c(G2[,2]),col="blue")# 生成网格K = 40;seqx1 = seq(min(G1[,1]),max(G1[,1]),length = K)seqx2 = seq(min(G1[,2]),max(G1[,2]),length = K)myGrid = expand.grid(z1=seqx1,z2=seqx2);plot(myGrid[,1],myGrid[,2])library(MASS) # 创建模型model.lda = lda(bothGroupsWithLabel[,3] ~bothGroupsWithLabel[,1]+bothGroupsWithLabel[,2] , data = bothGroupsWithLabel);Ypred = predict(model.lda, newdata=myGrid);Ypredgrid = Ypred$class
这是我的数据bothGroupsWithLabel
的一部分 V1 V2 V369 2.0683949 0.5779272 153 2.1261046 2.0420350 1118 -1.4502033 -1.4775360 2148 1.1705251 1.5437296 2195 0.3100763 -0.2594026 240 1.8573633 3.7717020 1
和myGrid z1 z21 0.1048024 -0.20341722 0.2227540 -0.20341723 0.3407055 -0.20341724 0.4586571 -0.20341725 0.5766086 -0.20341726 0.6945602 -0.2034172
我的网格由40*40个点组成,因此myGird
数据框的大小为1600行和2列。数据框bothGroupsWithLabel
由200行和3列组成,前两列是点的坐标,第三列用于标签。我的问题是当我调用predict(model.lda, newdata=myGrid)
时,我得到了这个警告信息:Warning message:'newdata'有1600行,但找到的变量有200行
我在这里错过了什么?谁能帮帮我?
回答:
问题出在你生成模型的方式上。当使用公式和data=...
时,最好只使用变量名。为了让它工作,你还必须使newdata
中的变量名匹配。所以,当你创建myGrid时,添加以下一行代码:
names(myGrid) = c("V1", "V2")
然后将你的最后几行改为:
model.lda = lda(V3 ~ V1 + V2 , data = bothGroupsWithLabel);Ypred = predict(model.lda, newdata=myGrid);Ypredgrid = Ypred$class
这样应该能得到你想要的结果。