You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

梯度下降迭代Epoch对应损失Cost绘图时numIterations未定义报错如何解决

问题分析与修改方案

错误根本原因:numIterations 是 gradientDescent 函数定义时的形参,作用域仅局限在函数内部,主代码的全局作用域中没有定义这个变量,因此调用 plt.plot 时会抛出未定义错误。你可以任选以下任意一种方案修改:

  • 方案1:直接匹配传入的迭代次数值
    你调用梯度下降函数时传入的迭代次数是100,直接把绘图代码中的numIterations替换为100即可:
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(my dataframe),100)
plt.plot(list(range(100)), cost_list, '-r')
  • 方案2:预先定义迭代次数为全局变量,函数调用和绘图复用变量
    这种方式可维护性更高,后续修改迭代次数只需要调整一处:
# 全局定义迭代次数参数
numIterations = 100
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(my dataframe),numIterations)
plt.plot(list(range(numIterations)), cost_list, '-r')
  • 方案3:直接用cost_list的长度生成横坐标
    梯度下降每迭代一次就会往cost_list里存入一个cost值,它的长度和实际迭代次数完全一致,不需要额外依赖迭代次数变量:
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(my dataframe),100)
plt.plot(range(len(cost_list)), cost_list, '-r')

额外注意:你贴出的gradientDescent函数存在缩进错误,Python是缩进敏感语言,函数定义后所有函数体内容都需要缩进4个空格,否则会抛出语法错误,修正后的函数参考:

def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.T
    cost_list=[]
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        cost = np.sum(loss ** 2) / (2 * m)
        cost_list.append(cost)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta,cost_list

内容的提问来源于stack exchange,提问作者Gamblet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 21:06:01