形状图裁剪/截断特征名称

2024-06-23

import csv
import pandas as pd
import numpy as np
from matplotlib import pyplot 
import shap
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
df1=pd.read_csv("./wine.data",sep=",",encoding='utf_8_sig')
X_train = df1
le = preprocessing.LabelEncoder()
X_train['alc_class'] = le.fit_transform(X_train.alc_class.values)
print(X_train.columns)

print(X_train.describe())


y = X_train['alc_class']
X = X_train.drop(columns='alc_class')
import xgboost as xgb


# split X and y into training and testing sets

from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30, random_state = 2100, stratify = y)

# import XGBClassifier
import xgboost as xgb
from sklearn.metrics import mean_squared_error
DM_train = xgb.DMatrix(data = X_train, 
                       label = y_train)
                       
                       
DM_test =  xgb.DMatrix(data = X_test,
                       label = y_test)


xgb_param_grid = {
     'colsample_bytree': np.linspace(0.5, 0.9, 2),
     'n_estimators':[30],
     'max_depth': [5],
     'learning_rate':[0.01],
     'alpha':[10],
     'objective':['binary:logistic'],
     'tree_method':['hist'],
     'min_child_weight': [1],
     'gamma': [0.5],
     'subsample': [0.6],

}

          
# instantiate the classifier 
xgb_clf = xgb.XGBClassifier(use_label_encoder=False, eval_metric="auc")


# perform 5 fold cross-validation using mean square error as a scoring method
grid_mse = GridSearchCV(estimator = xgb_clf, param_grid = xgb_param_grid, scoring = 'neg_mean_squared_error', cv = 5, verbose = 1)

# Fit grid_mse to the data, get best parameters and best score (lowest RMSE)

grid_mse.fit(X_train, y_train)



print("Best parameters found: ",grid_mse.best_params_)
print("Lowest RMSE found: ", np.sqrt(np.abs(grid_mse.best_score_)))


#Predict using the test data


y_pred = grid_mse.predict(X_test)
y_pred_prob = grid_mse.predict_proba(X_test)


print("Root mean square error for test dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_test, y_pred)), 2)))



from sklearn.metrics import accuracy_score, roc_curve, auc,recall_score,precision_score, precision_recall_curve,f1_score, classification_report, confusion_matrix,roc_auc_score


print('XGBoost model accuracy score: {0:0.4f}'. format(accuracy_score(y_test, y_pred)))
print('XGBoost model F1 score: {0:0.4f}'. format(f1_score(y_test, y_pred, average='weighted')))

precision, recall, thresholds = precision_recall_curve(y_test, y_pred)
area = auc(recall, precision)
print("----------------")
print("\n\n Evaluation Metrics \n\n")


aucroc_score = roc_auc_score(y_test, y_pred_prob[:,1])
print("Area Under ROC Curve: ",aucroc_score)
# roc curve for models
fpr, tpr, thresh = roc_curve(y_test, y_pred_prob[:,1], pos_label=1)

# roc curve for tpr = fpr 
random_probs = [0 for i in range(len(y_test))]
p_fpr, p_tpr, _ = roc_curve(y_test, random_probs, pos_label=1)


print("confusion_matrix ", confusion_matrix(y_test,y_pred))
print("classification_report ", classification_report(y_test,y_pred))


explainer = shap.TreeExplainer(grid_mse.best_estimator_)
shap_values = explainer(X_train)
shap.plots.beeswarm(shap_values, plot_size = 1.8, max_display = 13)


print(grid_mse.best_estimator_.feature_importances_)
for col,score in zip(X_train.columns,grid_mse.best_estimator_.feature_importances_):
    print('%s, %0.3f ' %(col,score))
  1. 我有很长的特征名称,我绘制了蜂群沙普利图,并且特征名称被截断。我希望在 y 轴上显示完整的功能名称。任何帮助将不胜感激。
  2. 我尝试过更改绘图大小,但没有成功。

添加一个标志来隐藏绘图。然后使用紧凑的 bbox 布局保存到输出:

path = 'save_path_here.png'
shap.plots.beeswarm(shap_values, plot_size = 1.8, max_display = 13, show=False)
plt.savefig(path, bbox_inches='tight', dpi=300)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

形状图裁剪/截断特征名称 的相关文章

随机推荐

  • Elastic Search:聚合随机顺序?

    是否可以进行随机顺序的聚合 好像只有asc或者desc可能 aggs genders terms field gender order count asc 对的 这是可能的 是这样做的 aggs genders terms field ge
  • Algolia 初始搜索参数 instantsearch.js

    我有一个索引 我试图在其中传递 algolia 中查询的初始值 我正在使用 instantsearch js 现在它只是从我的索引加载所有内容 如何在页面加载时将初始值传递给索引 例如Select from index where Cate
  • 如何强制 Visual Studio 2010 重新加载磁盘上已更改的文件和项目?

    我经常使用命令行工具对已加载到 Visual Studio 2010 中的文件和项目进行源代码管理更新 在以前的版本中 当我执行此操作时 我可以通过执行 全部保存 来强制 Visual Studio 注意到并加载更改 这在 Visual S
  • 如何更改 Mediawiki 导航侧边栏和页脚中的字体大小和颜色?

    我的网站是使用 Mediawiki 开发的 我有以下问题 如何更改导航侧边栏和页脚中的字体大小和字体颜色 我正在使用矢量皮肤 但很难找到进行这些更改的正确方法 对于导航 在你的CSS中搜索 div mw panel div portal d
  • 将数据保存到 iOS 的最佳方式?

    在我的应用程序 iOS 5 中 我想保存数据 我想节省债务 所以就是 加或减钱 金额 以及有债务的人的姓名 或您有债务的人的姓名 但我不知道如何保存数据 NSUserdefaults Core data SQLite 也许你可以告诉我拯救他
  • WebClient 上的 Exchange() 会抛出哪些异常?

    我已经实现了一个服务 它使 ReST 调用其他服务来实现其部分功能 我正在使用反应式WebClient为此 类似 webClient post uri contentType accept header syncBody someReque
  • 处理续集迁移和初始化的工作流程?

    我不明白续集迁移工作流程是如何工作的 我有一个新建项目 数据库是使用 SQL 脚本设计的 我们用了sequelize auto之后生成模型 我现在需要生成一个迁移文件 以便我可以运行 CLI 来运行 SQL 查询 为本地配置的数据库创建包含
  • 操作系统如何选择正确的 ico/favicon 大小?

    基于此 stackoverflow 讨论 https stackoverflow com questions 1526747 ideal size for ico 可以在单个文件中提供各种大小 并且 操作系统将选择最好的一个来显示 这是如何
  • mod_rewrite 仅适用于 GET

    这是一个不太可能的事情 但我希望找到一个简单的解决方法来解决一个奇怪的错误 该错误仅在应用程序省略 推断查询字符串时才会出现 在深入研究一千行缩小的第三方 javascript 之前 我想了解是否可以使用 mod rewrite 自动应用查
  • 如何使用 python 查找 iframe 中按钮的 XPath?

    我在 iframe 中有以下 html 对象 提交 按钮的 html 代码 https i stack imgur com pe3rZ png 我需要找到它的 XPath 才能单击 提交 按钮 但找不到它 XPath 助手仅显示 ifram
  • 使用 Tomcat 的外部 LDAP JNDI 连接

    我想知道如何使用 TOMCAT 中的 JNDI 配置连接外部 LDAP 我的代码是这样的 try InitialContext iniCtx new InitialContext ctx LdapContext iniCtx lookup
  • 如何使用纸对话高分子元件?

    我通过添加开始和结束标签来使用该元素
  • pymssql 包不适用于 aws 中的 lambda

    我们如何为 lambda 创建 pymssql 包 我尝试使用创建它 pip install pymssql t 当我运行 lambda 函数时 它抱怨说 无法导入模块 lambda function 没有名为 lambda functio
  • 如何在 SwiftUI 中实现触发 switch case 的左或右 DragGesture() ?

    我在视图中创建了一个 DragGesture 无论用户向左还是向右滑动 它都应该选择 State Bool 问题是只检测到向右滑动 如何使用 gesture 捕获用户在屏幕上向左还是向右滑动 import SwiftUI struct Sw
  • 为什么要给伪元素添加块级别?

    从本页的代码 http css tricks com snippets css sticky footer http css tricks com snippets css sticky footer page wrap min heigh
  • 视图和表在性能上的差异

    对于包含大量数据的表来说什么是最好的 我有一个存储过程 可以根据一些过滤器创建报告 在我的 SP 中 我读取表格并放入所有内部联接和公式 然后在放置过滤器的 where 条件中 谈论性能什么更好 创建一个包含所有联接的视图或读取表 就像我正
  • 无法在静态方法中创建静态变量?

    为什么这不起作用 public static int GetListOfAllDaysForMonths static int MonthDays new int 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
  • 从 Angular 2 中的 FileReader 获取值

    我有以下组件加载文件并将其内容绑定为字符串 export class NgCsvComponent Input csv any Output csvChange any new EventEmitter public localCsv an
  • 如何隐藏 UITableViewCells 同时不违反自动布局约束

    我目前正在开发一个应用程序来学习 iOS 编程和 Swift 我有一个视图 其中包含两个主要子视图 一个 MKMapView 和一个 UITableView 当在 MapView 中选择某个注释时 我希望隐藏 TableView 中的某些单
  • 形状图裁剪/截断特征名称

    import csv import pandas as pd import numpy as np from matplotlib import pyplot import shap from sklearn import preproce