自定义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
相关产品推荐
相关产品推荐

