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

自定义Logistic Regression代码RuntimeWarning及NaN输出问题排查

Logistic Regression 成本函数输出NaN及log警告问题解决

问题根源分析

你遇到的RuntimeWarning: invalid value encountered in log和成本函数输出NaN,是由代码中多处错误导致的:

  • 假设函数h中:参数X被误写为小写x,且sigmoid公式因运算符优先级错误计算出错
  • 成本函数J中:调用h时使用了未定义的小写x,且成本公式的符号、结构不符合逻辑回归定义
  • 读取文件的while循环存在缩进错误,导致数据读取异常

修正后的关键代码片段

修正后的假设函数h

def h(X,theta):  
    z = X*theta.T
    sigmoid = 1/(1 + np.exp(-z))
    return sigmoid

修正后的成本函数J

def J(theta, X, y):  
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    h_val = h(X,theta)
    first = np.multiply(y, np.log(h_val))
    second = np.multiply((1-y), np.log(1-h_val))
    total = -np.sum(first + second) / len(X)
    return total

额外注意事项

务必修正读取文件代码的缩进,保证while循环内的语句都正确缩进,避免数据读取不完整或格式错误导致后续计算异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:16:10