代码中的 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
了!🚀