方法之间传参,借用main

代码中的 X_train 是在 train_and_evaluate() 方法中定义的,但 plot_feature_importance() 需要使用它。由于 X_train 不是 main() 里的变量,plot_feature_importance() 直接访问它时会报 NameError


解决方案

方法 1(推荐):修改 train_and_evaluate(),返回 X_train

既然 train_and_evaluate() 里定义了 X_train,最好的做法是让它返回 X_train,然后 main() 里接收并传递给 plot_feature_importance()

修改 train_and_evaluate()
def train_and_evaluate(X, y):
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    model = RandomForestClassifier()
    model.fit(X_train, y_train)
    
    return model, X_train  # 让 X_train 也返回

修改 main()
def main():
    data = load_data()
    X_processed, y = data_preprocessing(data)
    
    # 训练模型并获取 X_train
    model, X_train = train_and_evaluate(X_processed, y)

    # 获取特征名称(确保 X_train 是 DataFrame)
    feature_names = X_train.columns.tolist()  

    # 传递 X_train 给 plot_feature_importance()
    plot_feature_importance(model, X_train, feature_names)

修改 plot_feature_importance()
def plot_feature_importance(model, X_train, feature_names):
    importances = model.feature_importances_
    indices = np.argsort(importances)[::-1]

    plt.bar(range(X_train.shape[1]), importances[indices], align="center")
    plt.xticks(range(X_train.shape[1]), feature_names, rotation=90)
    plt.xlabel("Feature Index")
    plt.ylabel("Feature Importance")
    plt.title("Feature Importance Plot")
    plt.show()

这样 X_train 就能从 train_and_evaluate() 传递到 plot_feature_importance(),不会再报 NameError 了!🚀


方法 2(不推荐):使用全局变量

另一种方式是 使用全局变量 X_train,但不推荐,因为这样代码不清晰,容易导致变量污染:

global X_train  # 声明全局变量
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

然后 plot_feature_importance() 直接使用 X_train,但这样代码的可维护性差,不建议。


总结

推荐方法 1(最佳)

  • 修改 train_and_evaluate(),让它返回 X_train,并在 main() 里传递给 plot_feature_importance()
    不推荐方法 2(使用 global X_train
  • 全局变量污染代码,可读性差

最终修改后,plot_feature_importance() 就能正确访问 X_train 了!🚀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值