【发布时间】:2016-09-25 21:23:32
【问题描述】:
我有一个在 R 中使用梯度下降的多变量线性回归的工作实现。我想看看我是否可以使用我必须运行的随机梯度下降。我不确定这是否真的效率低下。例如,对于每个 α 值,我想执行 500 次 SGD 迭代,并且能够指定每次迭代中随机选取的样本数。这样做会很好,这样我就可以看到样本数量如何影响结果。我在处理小批量时遇到了麻烦,我希望能够轻松绘制结果。
这是我目前所拥有的:
# Read and process the datasets
# download the files from GitHub
download.file("https://raw.githubusercontent.com/dbouquin/IS_605/master/sgd_ex_data/ex3x.dat", "ex3x.dat", method="curl")
x <- read.table('ex3x.dat')
# we can standardize the x vaules using scale()
x <- scale(x)
download.file("https://raw.githubusercontent.com/dbouquin/IS_605/master/sgd_ex_data/ex3y.dat", "ex3y.dat", method="curl")
y <- read.table('ex3y.dat')
# combine the datasets
data3 <- cbind(x,y)
colnames(data3) <- c("area_sqft", "bedrooms","price")
str(data3)
head(data3)
################ Regular Gradient Descent
# http://www.r-bloggers.com/linear-regression-by-gradient-descent/
# vector populated with 1s for the intercept coefficient
x1 <- rep(1, length(data3$area_sqft))
# appends to dfs
# create x-matrix of independent variables
x <- as.matrix(cbind(x1,x))
# create y-matrix of dependent variables
y <- as.matrix(y)
L <- length(y)
# cost gradient function: independent variables and values of thetas
cost <- function(x,y,theta){
gradient <- (1/L)* (t(x) %*% ((x%*%t(theta)) - y))
return(t(gradient))
}
# GD simultaneous update algorithm
# https://www.coursera.org/learn/machine-learning/lecture/8SpIM/gradient-descent
GD <- function(x, alpha){
theta <- matrix(c(0,0,0), nrow=1)
for (i in 1:500) {
theta <- theta - alpha*cost(x,y,theta)
theta_r <- rbind(theta_r,theta)
}
return(theta_r)
}
# gradient descent α = (0.001, 0.01, 0.1, 1.0) - defined for 500 iterations
alphas <- c(0.001,0.01,0.1,1.0)
# Plot price, area in square feet, and the number of bedrooms
# create empty vector theta_r
theta_r<-c()
for(i in 1:length(alphas)) {
result <- GD(x, alphas[i])
# red = price
# blue = sq ft
# green = bedrooms
plot(result[,1],ylim=c(min(result),max(result)),col="#CC6666",ylab="Value",lwd=0.35,
xlab=paste("alpha=", alphas[i]),xaxt="n") #suppress auto x-axis title
lines(result[,2],type="b",col="#0072B2",lwd=0.35)
lines(result[,3],type="b",col="#66CC99",lwd=0.35)
}
找到使用sgd()的方法是不是更实用?我似乎无法弄清楚如何使用 sgd 包获得我想要的控制级别
【问题讨论】:
-
sgd有两个参数,model.control和sgd.control两者都有一个相当大的选项列表,你可以通过。你想要更多的控制权吗?你还想做什么? -
也许我只是不明白如何设置样本数量。你知道用 sgd 使用多元线性回归的好例子吗?
-
我没有看到那个选项。你总是可以自己做,即
sample500 的总数,并使用模型中的数据子集。记得set.seed -
?sgd有一个多变量线性示例,尽管它非常简单。还有vignette -
检查源代码,
model.control和sgd.control似乎由sgd:::valid_model_control和sgd:::valid_sgd_control控制,尽管我没有看到观察次数的选项。鉴于 sgd 保证在批量大小 == 1 时是最佳的,因此可能没有选项。通常批量大小仅用于控制学习时间(计算时间,而不是迭代次数)......由于包正在积极开发中,我建议你raise an issue with the authors......即使你使用下面的rawr的包装器跨度>
标签: r gradient-descent stochastic