实现带正则化的梯度下降代码时遇TypeError错误的解决方法
解决带正则化梯度下降代码中的TypeError错误
你的梯度下降代码如下:
def gradient_desc(X, Y, w_in, b_in, cost_f, grad_f, alp, num, lambda_): m = len(X) # An array to store cost J and w's at each iteration primarily for graphing later J_history = [] w_history = [] for i in range(num): # Calculate the gradient and update the parameters dj_db, dj_dw = grad_f(X, Y, w_in, b_in, lambda_) # Update Parameters using w, b, alpha and gradient w_in = w_in - alpha * dj_dw b_in = b_in - alpha * dj_db # Save cost J at each iteration if i<100000: # prevent resource exhaustion J_history.append(cost_f(X, Y, w_in, b_in, lambda_)) # Print cost every at intervals 10 times or as many iterations if < 10 if i% math.ceil(num/10) == 0: w_history.append(w_in) print(f"Iteration {i:4}: Cost {float(J_history[-1]):0.2e} ") return w_in, b_in, J_history, w_history #return w and J,w history for graphing
报错信息:
TypeError: float() argument must be a string or a real number, not 'NoneType'
错误原因
这个错误说明执行float(J_history[-1])时,J_history[-1]是None——也就是cost_f(X, Y, w_in, b_in, lambda_)调用后没有返回有效数值。常见诱因:
cost_f函数缺失返回逻辑:你定义的代价函数可能漏写了return语句,或者没有正确返回计算出的代价结果。cost_f参数不匹配:调用cost_f时传递的参数顺序、数量和函数定义不一致,导致函数无法正常计算代价。- 代码存在隐藏问题:函数参数定义为
alp,但内部更新参数时用的是alpha,这会触发NameError,需统一参数名。
解决步骤
- 补全
cost_f的返回语句:打开cost_f的定义,确认函数末尾有返回代价数值的语句。示例:def cost_f(X, Y, w, b, lambda_): # 正则化代价计算逻辑 J = ... # 你的代价计算代码 return J # 必须添加这一行返回计算结果 - 校验
cost_f参数匹配性:确保cost_f的参数列表和调用时的参数完全对应,即顺序为(X, Y, w, b, lambda_)、数量一致。 - 统一参数名:将函数定义中的
alp改为alpha,或者把内部的alpha替换成alp,保持参数名一致。
内容的提问来源于stack exchange,提问作者SM Hamza Mehdi
相关产品推荐
相关产品推荐

