BEN老师:
PYTHONI好多函数用的不熟,我的作业是用R写的,我有问题,向您请教:
1.6万样本放在一个数据集时,我一直对因变量price取log,建模后R方=0.602,但vif异方差一直显著,我认为是样本量太多的问题,于是按区生成六个子集,用东城区2873条样本建模,但R方只有0.23,异方差的问题还是没有解决。
我的问题:
1、线性回归建模 的样本量多少比较合适, 1.6万降到2700,R方为什么差的这么多?
2、异方差的问题,取不取log都没变化,还有什么别的方法除去异方差?
谢谢老师
###################第四周作业--二手房分析
#数量整理
setwd('E:/finance_R')
sndHsPr<-read.csv("sndHsPr.csv")
snd_dc<-sndHsPr[which(sndHsPr$dist=="dongcheng"),c(2,3,4,5,6,7,8)] #2783条建模
snd_dc$subway<-as.factor(snd_dc$subway)#是否地铁,改为因子
snd_dc$school<-as.factor(snd_dc$school) #是否学区,改为因子
require(mice)
md.pattern(snd_dc) # 无缺失值
attach(snd_dc)
######因变量分析:价格
summary(price) #价最低1.8万,最高14万,均值6.1万
hist(price,prob=T,main='房价/平米 直方图',breaks=30);lines(density(price)) #右偏
require(e1071) #R基础包里没有,e1071包有峰度和偏度函数
skewness(price) #[1] -0.02322729
qqnorm(price);qqline(price) #QQ图,正态
boxplot(snd_dc$price)
table(snd_dc$price<quantile(snd_dc$price,0.01)) #28 个小于1%分位点
table(snd_dc$price>quantile(snd_dc$price,0.99)) #28 个大于99%分位点
up<-which(snd_dc$price>quantile(snd_dc$price,0.99)) #取行号
snd_dc$price[up]<- quantile(snd_dc$price,0.99) #盖帽
low<-which(snd_dc$price<quantile(snd_dc$price,0.01)) #取行号
snd_dc$price[low]<- quantile(snd_dc$price,0.01) #盖帽
boxplot(snd_dc$price) #无离群值
##########自变量分析
anova(lm(price~floor)) #0.006844 p值显著,楼层对房价有影响
t.test(price~subway,equal=F) #p-value < 2.2e-16p值显著,地铁对房价有影响
t.test(price~school,equal=F) #p-value < 2.2e-16,p值显著,学区对房价有影响
cor.test(AREA,price)#负相关,面积与价格负弱相关-0.1429359
cor.test(roomnum,price)#不相关,0.002223121
cor.test(halls,price) #不相关0.01121376
#建模数据准备-哑变量处理
dummy<-dummyVars(~.,data=snd_dc,fullRank=T) #哑变量处理,fullRank会少一列哑变量
dc_jm<-data.frame(predict(dummy,newdata=snd_dc)) #最终建模数据框dc_jm整理完成
########################### 建模
model1<-lm(price~roomnum+halls+AREA+floor.low+floor.middle+subway.1
+school.1,data=dc_jm)
summary(model1)
step(model1,direction="both") #无变量可删除
dc_jm$pred<-predict(model1) #预测
dc_jm$res<-resid(model1) #残差
plot(dc_jm$res~dc_jm$pred,data=dc_jm)
require(lmtest)
bptest(model1) # p-value < 2.2e-16 显著 ,有异方差
dc_jm$price_ln<-log(dc_jm$price)
model2<-lm(price_ln~roomnum+halls+AREA+floor.low+floor.middle+subway.1
+school.1,data=dc_jm)
summary(model2) #model2 R方=0.2343 比model1 R方=0.203 有提高
require(car)
vif(model2) #无共线性问题
bptest(model2) #BP = 343.15, df = 7, p-value < 2.2e-16 还是有异方差问题
# dc_jm_pred$pred<-predict(model2,newdata=dc_jm_pred)
#手动录入一条 ,预测 log值=11.27731
#预测值= exp(11.27731)=79008.44