gpt4 book ai didi

python - Python 的批量梯度下降不收敛

转载 作者:行者123 更新时间:2023-11-30 10:00:03 25 4
gpt4 key购买 nike

这是我用于此练习的 Jupyter Notebook:https://drive.google.com/file/d/18-OXyvXSit5x0ftiW9bhcqJrO_SE22_S/view?usp=sharing

我正在练习简单的线性回归 this数据集,这是我的参数:

sat = np.array(data['SAT'])
gpa = np.array(data['GPA'])
theta_0 = 0.01
theta_1 = 0.01
alpha = 0.003
cost = 0
m = len(gpa)

我尝试通过将成本函数计算转换为矩阵并执行元素明智的操作来优化它。这是我得出的公式:

成本函数优化: Cost function optimization (image)

成本函数

def calculateCost(matrix_x,matrix_y,m):
global theta_0,theta_1
cost = (1 / (2 * m)) * ((theta_0 + (theta_1 * matrix_x) - matrix_y) ** 2).sum()
return cost

我也尝试对梯度下降做同样的事情。

梯度下降

def gradDescent(alpha,matrix_x,matrix_y):
global theta_0,theta_1,m,cost
cost = calculateCost(sat,gpa,m)
while cost > 1
temp_0 = theta_0 - alpha * (1 / m) * (theta_0 + theta_1 * matrix_x - matrix_y).sum()
temp_1 = theta_1 - alpha * (1 / m) * (matrix_x.transpose() * (theta_0 + theta_1 * matrix_x - matrix_y)).sum()
theta_0 = temp_0
theta_1 = temp_1

我不完全确定这两种实现是否正确。该实现返回了 114.89379821428574 的成本,不知何故,这就是我绘制成本图时“下降”的样子:

梯度下降图:

Gradient descent graph

如果我正确地实现了成本函数梯度下降,请纠正我,并尽可能提供解释,因为我仍然是多变量微积分的初学者。谢谢。

最佳答案

该代码有很多问题。

首先,这些错误背后的两个主要问题:

1)线路

temp_1 = theta_1 - alpha * (1 / m) * (matrix_x.transpose() * (theta_0 + theta_1 * matrix_x - matrix_y)).sum()

特别是矩阵乘法matrix_x.transpose() * (theta_0 + ...)* 运算符执行逐元素乘法,结果大小为 20x20,而您期望的渐变大小为 1x1 code> (当您更新单个实数变量 theta_1 时。

2) 梯度计算中的 while cost>1: 条件。您永远不会在循环中更新成本...

这是您的代码的有效版本:

import numpy as np
import matplotlib.pyplot as plt

sat=np.random.rand(40,1)
rand_a=np.random.randint(500)
rand_b=np.random.randint(400)
gpa=rand_a*sat+rand_b
theta_0 = 0.01
theta_1 = 0.01
alpha = 0.1
cost = 0
m = len(gpa)

def calculateCost(matrix_x,matrix_y,m):
global theta_0,theta_1
cost = (1 / 2 * m) * ((theta_0 + (theta_1 * matrix_x) - matrix_y) ** 2).sum()
return cost

def gradDescent(alpha,matrix_x,matrix_y,num_iter=10000,eps=0.5):
global theta_0,theta_1,m,cost
cost = calculateCost(sat,gpa,m)
cost_hist=[cost]
for i in range(num_iter):
theta_0 -= alpha * (1 / m) * (theta_0 + theta_1 * matrix_x - matrix_y).sum()
theta_1 -= alpha * (1 / m) * (matrix_x.transpose().dot(theta_0 + theta_1 * matrix_x - matrix_y)).sum()
cost = calculateCost(sat,gpa,m)
cost_hist.append(cost)
if cost<eps:
return cost_hist

if __name__=="__main__":

print("init_cost==",cost)
cost_hist=gradDescent(alpha,sat,gpa)
print("final_cost,num_iters",cost,len(cost_hist))
print(rand_b,theta_0,rand_a,theta_1)
plt.plot(cost_hist,linewidth=5,color="r");plt.show()

最后,编码风格本身虽然不是造成错误的原因,但绝对是一个问题。一般来说,全局变量只是不好的做法。它们只会导致容易出错且难以维护的代码。最好将它们存储在小型数据结构中并将它们传递给函数。在您的情况下,您可以将初始参数放入列表中,将它们传递给梯度计算函数,并在最后返回优化后的参数。

关于python - Python 的批量梯度下降不收敛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59406021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com