Python中用带return的for循环实现多分类编码器的问题排查
问题原因
你的自定义编码器存在两个核心逻辑错误:
- 循环变量使用错误:
range(len(x))生成的是整数索引序列,你直接用索引值和"yes"/"no"字符串做判断,永远无法匹配成功,最终只会返回9999 - 逻辑提前终止:循环内部直接写return语句,第一次迭代就会直接返回单个值,不会遍历整个输入列表完成全量转换
正确实现
原生Python实现
不需要依赖第三方库,直接遍历列表元素完成转换:
def encoder(x): res = [] for item in x: if item == "yes": res.append(1) elif item == "no": res.append(0) else: res.append(9999) return res y_train = ["yes", "no", "yes", "problem"] y_train = encoder(y_train) # 转换后结果:[1, 0, 1, 9999]
Numpy向量化实现
和你原有的np.where方案兼容,代码更简洁,处理大规模数据时性能更高:
import numpy as np y_train = np.array(["yes", "no", "yes", "problem"]) # 嵌套where实现三分支判断 y_train = np.where(y_train == "yes", 1, np.where(y_train == "no", 0, 9999)) # 转换后结果:array([ 1, 0, 1, 9999])
内容的提问来源于stack exchange,提问作者Jaroslav Kotrba
相关产品推荐
相关产品推荐

