【Python机器学习系列】机器学习模型微调---随机搜索(案例)

人工智能
后台-插件-广告管理-内容页头部广告(手机)

这是我的第245篇原创文章。

一、引言

如果探索的组合数量较少时,网格搜索是一种不错的方法,但当超参数的搜索范围较大时,通常会优先选择使用 RandomizedSearchCV 。它与 GridSearchCV 用法相似,但它不会尝试所有可能的组合,而是在每次迭代中为每个超参数选择一个随机值,然后对一定数量的随机组合进行评估,这种方法有两个显著的好处。

如果运行随机 1000 个迭代,那么将会探索每个超参数的 1000 个不同的值(而不像网格搜索方法那样每个超参数仅探索少量几个值)。通过简单地设置迭代次数,可以更好地控制要分配给超参数搜索的计算预算。

二、实现过程

数据准备与划分

# 准备数据data = pd.read_csv(r'Dataset.csv')df = pd.DataFrame(data)# 提取目标变量和特征变量target = 'target'features = df.columns.drop(target)print(data["target"].value_counts()) # 顺便查看一下样本是否平衡# 划分训练集和测试集X_train, X_test, y_train, y_test = train_test_split(df[features], df[target], test_size=0.2, random_state=0)

2.1 随机搜索参数建模

# 模型的构建与训练param_distribs = {    # 均匀离散随机变量    'n_estimators': randint(low=1, high=200),    'max_features': randint(low=7, high=9),}model = RandomForestClassifier(random_state=42)rnd_search = RandomizedSearchCV(model, param_distributions=param_distribs,                                n_iter=10, cv=5, scoring='neg_mean_squared_error', random_state=42)rnd_search.fit(X_train, y_train)

2.2查看评分最高的超参数组合

print(grid_search.best_params_)
 

2.3查看当前的最佳估算器

输出只显示非默认的参数

final_model = grid_search.best_estimator_print(final_model)
 

2.4计算的各种超参数组合的评分

cvres = grid_search.cv_results_for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):    print(np.sqrt(-mean_score), params)
 

模型推理与评价

# 模型推理与评价y_pred = final_model.predict(X_test)y_scores = final_model.predict_proba(X_test)acc = accuracy_score(y_test, y_pred) # 准确率acccm = confusion_matrix(y_test, y_pred) # 混淆矩阵cr = classification_report(y_test, y_pred) # 分类报告fpr, tpr, thresholds = roc_curve(y_test, y_scores[:, 1], pos_label=1) # 计算ROC曲线和AUC值,绘制ROC曲线roc_auc = auc(fpr, tpr)plt.figure()plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver Operating Characteristic')plt.legend(loc="lower right")plt.show()
 

作者简介:

读研期间发表6篇SCI数据算法相关论文,目前在某研究院从事数据算法相关研究工作,结合自身科研实践经历持续分享关于Python、数据分析、特征工程、机器学习、深度学习、人工智能系列基础知识与案例。关注gzh:数据杂坛,获取数据和源码学习更多内容。

原文链接:

【Python机器学习系列】机器学习中的模型微调---随机搜索(案例+源码)

后台-插件-广告管理-内容页尾部广告(手机)
标签:

评论留言

我要留言

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。