rstudio编写梯度下降法代码
时间: 2024-03-02 10:43:33 浏览: 14
这里提供一个简单的线性回归模型的梯度下降法代码实现:
```r
# 生成样本数据
set.seed(123)
x <- rnorm(100)
y <- 2*x + rnorm(100)
# 初始化参数
theta0 <- 0
theta1 <- 0
learning_rate <- 0.01
epochs <- 1000
# 定义损失函数
cost_function <- function(x, y, theta0, theta1) {
sum((theta0 + theta1*x - y)^2)/(2*length(x))
}
# 定义梯度下降算法
gradient_descent <- function(x, y, theta0, theta1, learning_rate, epochs) {
cost_history <- rep(NA, epochs)
for (i in 1:epochs) {
# 计算梯度
d_theta0 <- sum(theta0 + theta1*x - y)/length(x)
d_theta1 <- sum((theta0 + theta1*x - y)*x)/length(x)
# 更新参数
theta0 <- theta0 - learning_rate*d_theta0
theta1 <- theta1 - learning_rate*d_theta1
# 计算损失函数值
cost_history[i] <- cost_function(x, y, theta0, theta1)
}
# 返回参数和损失函数值
list(theta0=theta0, theta1=theta1, cost_history=cost_history)
}
# 运行梯度下降算法
result <- gradient_descent(x, y, theta0, theta1, learning_rate, epochs)
# 打印参数估计值
cat("theta0:", result$theta0, "\n")
cat("theta1:", result$theta1, "\n")
# 绘制损失函数值随迭代次数的变化图
plot(result$cost_history, type="l", xlab="Epochs", ylab="Cost")
```
该代码实现了一个简单的线性回归模型的梯度下降算法,可以根据自己的需要进行修改和扩展。