该篇文章主要展示了利用R语言建立Logistic回归模型,并对新数据进行预测。
1. 数据背景:
(Sports2.csv)是用于客观性分析的体育文章数据.使用Amazon Mechanical Turk对1000篇体育文章标记了objective(客观)或subjective(主观),这是因变量的两个水平。试以该数据中的Label为因变量,PRP和VBN作为自变量做logistic回归,并对新的样本PRP=20和VBN=5进行判别其Label。
2 数据读取及预处理
运行程序:
e2<- read.csv('G:\\Sports2.csv') #Label赋值(二分类) e2[,1] <- as.character(e2[,1]) e2[,1] <- gsub("objective",0,e2[,1]) #objective为0 e2[,1] <- gsub("subjective",1,e2[,1])#subjective为1 e2[,1] <- as.numeric(e2[,1]) str(e2)
运行结果:
## 'data.frame': 1000 obs. of 9 variables: ## $ Label : num 0 0 0 0 0 0 0 0 0 0 ... ## $ PRP : int 2 5 0 2 9 6 2 7 10 15 ... ## $ VBN : int 0 9 2 1 6 1 3 10 4 6 ... ## $ imperative: int 0 0 0 1 1 0 0 3 3 3 ... ## $ Quotes : int 0 7 0 3 4 6 2 9 10 0 ... ## $ past : int 11 13 8 13 34 24 13 21 59 73 ... ## $ CC : int 7 1 8 7 33 17 1 5 49 13 ... ## $ JJS : int 0 0 0 0 0 0 0 0 0 0 ... ## $ WRB : int 0 0 0 0 0 0 0 0 0 0 ...
3 建立Logistic回归模型
运行程序:
attach(e2) e2_glm<-glm(Label~PRP+VBN,family = binomial(link = "logit")) summary(e2_glm)
运行结果:
## ## Call: ## glm(formula = Label ~ PRP + VBN, family = binomial(link = "logit")) ## ## Deviance Residuals: ## Min 1Q Median 3Q Max ## -3.046 -0.713 -0.541 0.847 2.089 ## ## Coefficients: ## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -2.06267 0.13795 -14.95 <2e-16 *** ## PRP 0.02991 0.01077 2.78 0.0055 ** ## VBN 0.09711 0.00932 10.41 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## (Dispersion parameter for binomial family taken to be 1) ## ## Null deviance: 1312.5 on 999 degrees of freedom ## Residual deviance: 1026.9 on 997 degrees of freedom ## AIC: 1033 ## ## Number of Fisher Scoring iterations: 4
由此得到初步的Logistic模型:
由数据结果可以看出,在0.01的显著性水平下,自变量PRP和VBN均通过显著性检验。
4 模型预测
运行程序:
detach(e2) xb<-predict(e2_glm,data.frame(PRP=20,VBN=5)) p=exp(xb)/(1+exp(xb));p
运行结果:
## 1 ## 0.2731
所以结果为0,属于objective (客观)。