计算最佳调整R²时遇TypeError:numpy.ndarray与tuple无法比较
问题定位与修复
错误原因
报错TypeError: '>' not supported between instances of 'numpy.ndarray' and 'tuple'的核心问题出在find_the_best_model函数的赋值逻辑:
- 初始
current_best是二元元组("Placeholder", 0),第二个元素为R²数值 - 当找到更优R²时,错误将
current_best赋值为(col, current_best),导致current_best变成嵌套元组(例如('weight', ('Placeholder', 0))) - 下一次循环时,
current_best[1]不再是数值,而是元组,与calculate_Rsquared(numpy标量)进行>比较时触发类型错误
修复代码
修改find_the_best_model函数中的赋值语句,将当前列名和对应R²值组成新的二元元组:
def find_the_best_model(df, response): current_best = ("Placeholder", 0) for col in df.columns.drop(response): calculate_Rsquared = create_SLR_model(df, response, col).fit().rsquared if calculate_Rsquared > current_best[1]: # 修正赋值逻辑:存储列名和当前计算的R²值 current_best = (col, calculate_Rsquared) return current_best
额外优化提示
- 你注释中提到要找最佳调整R²,但原代码用的是普通R²,若需调整R²,需将
.rsquared替换为.rsquared_adj - 循环前可检查
df.columns.drop(response)是否非空,避免空循环无意义执行
内容的提问来源于stack exchange,提问作者codec_8888
相关产品推荐
相关产品推荐

