stata剔除数据(在Stata上实现GridSearch)
stata剔除数据(在Stata上实现GridSearch)
Gird Search是穷举所有超参数的组合从中选出最优组合的方法。Stata软件的实际操作方法如下。
/*生成实验数据*/
set obs 600
set seed 123456
gen x1= uniform()
gen x2= uniform()
gen x3= uniform()
gen x4= uniform()
/* signal to noise ratio*/
local SNR=4
gen y= 30 *(x1-0.5)^2 2*(x2^(-.5)) x3
qui sum y
local sigma = sqrt(r(Var)/`SNR')
replace y=y uniform() * `sigma'
/*使用Gridsearch方法查找超参数c和gamma的最优组合*/
gen c=.
gen gamma=.
local i=0
/*用foreach做个双重嵌套循环*/
foreach c of numlist 0.001 0.01 1 10 100 1000 10000 {
foreach gamma of numlist 0.0001 0.001 0.01 0.1 1 10{
local i=`i' 1
replace c= `c' in `i'
replace gamma= `gamma' in `i'
svmachines y x1 x2 x3 x4 c(`c') gamma(`gamma') type(svr)
predict pred`i'
}
}
/*计算每个超参数组合的均方误差(MSE)并保存*/
/*6x7=42(gamma和c可能的组合数)*/
local i=0
foreach inter of numlist 1/42 {
local i=`i' 1
egen total`i'=total(((y-pred`i')^2))
}
local i=0
foreach inter of numlist 1/42 {
local i=`i' 1
gen mse`i'=total`i'/(_N) in `i'
}
egen mse=rowtotal(mse1-mse42)
droppred1-pred42total1-total42mse1-mse42
将结果画图可以看出超参数gamma值及c值越高,模型的均方误差就越小。
例中支持向量机的超参数建议设置[gamma=10,c=10000]。
统计学应用,数据分析,计量经济分析知识交流及分享。