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

运行compute_gradient函数出现NameError: name 'x'未定义的求助

问题解决:线性回归梯度计算函数的错误修复

1. 解决NameError: name 'x' is not defined

这个错误直接原因是调用compute_gradient函数时未传入x参数,或者传入的变量名与函数参数名不匹配(Python大小写敏感,比如用了X而非x)。

错误调用示例:

# 漏掉x参数
compute_gradient(y=y_data, w=0, b=0)
# 变量名不匹配
compute_gradient(X=x_data, y=y_data, w=0, b=0)

正确调用示例:

import numpy as np
# 示例样本数据
x = np.array([5.0, 10.0, 15.0])
y = np.array([10.0, 20.0, 30.0])
w_init = 0
b_init = 0

# 传入所有参数,确保x参数名对应
dj_dw, dj_db = compute_gradient(x, y, w_init, b_init)

2. 修复函数内部逻辑bug

你的函数还有几处逻辑错误,即使解决NameError也会运行异常,一并修正:

  • 变量名不一致:用n = x.shape[0]获取样本数,但后续除以未定义的m,统一改为n
  • 梯度平均时机错误:将除以样本数的操作放在for循环内部,导致每次循环重复做平均,应移到循环结束后
  • 梯度计算错误:dj_dw_i中误写为[i],实际应为x[i](线性回归对w的梯度公式是(f_wb - y[i]) * x[i])

修正后的完整函数代码:

# UNQ_C2
# GRADED FUNCTION: compute_gradient
def compute_gradient(x, y, w, b): 
 """
    Computes the gradient for linear regression 
    Args:
      x (ndarray): Shape (m,) Input to the model (Population of cities) 
      y (ndarray): Shape (m,) Label (Actual profits for the cities)
      w, b (scalar): Parameters of the model  
    Returns
      dj_dw (scalar): The gradient of the cost w.r.t. the parameters w
      dj_db (scalar): The gradient of the cost w.r.t. the parameter b     
 """
    
# Number of training examples
n = x.shape[0]
    
# You need to return the following variables correctly
dj_dw = 0
dj_db = 0
    
### START CODE HERE ###     
    
for i in range(n):
    f_wb = w * x[i] + b
    dj_db_i = f_wb - y[i]
    dj_db += dj_db_i
    
    dj_dw_i = (f_wb - y[i]) * x[i]
    dj_dw += dj_dw_i 

# 循环结束后计算平均梯度
dj_dw = dj_dw / n
dj_db = dj_db / n
    
### END CODE HERE ### 
        
return dj_dw, dj_db

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:20:32