# 准备数据
data = pd.read_csv(r'Dataset.csv')
df = pd.DataFrame(data)
## 数据基本信息
cat_cols = [col for col in df.columns if df[col].dtype == "object"] # 类别型变量名
num_cols = [col for col in df.columns if df[col].dtype != "object"] # 数值型变量名
# 提取目标变量和特征变量
target = 'target'
features = df.columns.drop(target)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(df[features], df[target], test_size=0.2, random_state=0)
2.2 模型训练与保存
利用训练集进行训练模型:
# 模型的构建与训练
model = RandomForestClassifier()
model.fit(X_train, y_train)
# 使用 pickle 保存模型
with open('./random_forest_model.pkl', 'wb') as file:
pickle.dump(model, file)
模型保存为pkl文件:
2.3 模型推理与评价
加载训练好的模