• Friedman检验和Nemenyi检验画图代码


    关注 码龄 粉丝数 原力等级 -- 被采纳 被点赞 采纳率 NO_10969 2024-05-09 15:32 采纳率: 60% 浏览 21 首页/ 编程语言 / Friedman检验和Nemenyi检验画图代码 python数据分析机器学习 # 初始化分类器 lg=LogisticRegression(random_state=42) rf = RandomForestClassifier(n_estimators=100, random_state=42) clf = DecisionTreeClassifier(random_state=42) # 交叉验证 skfolds=StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # 性能指标列表 performance_scores = { 'lg': { 'recall': [], 'f1': [], 'auc': []}, 'rf': { 'recall': [], 'f1': [], 'auc': []}, 'clf': {'recall': [], 'f1': [], 'auc': []} } # 交叉验证过程 for train_index, test_index in skfolds.split(X, y): X_train, X_test = X.iloc[train_index], X.iloc[test_index] y_train, y_test = y.iloc[train_index], y.iloc[test_index] # 逻辑回归模型训练和评估 lg.fit(X_train, y_train) y_pred1 = lg.predict(X_test) y_score1 = lg.predict_proba(X_test)[:, 1] fpr1, tpr1, _ = metrics.roc_curve(y_test, y_score1) roc_auc1 = metrics.auc(fpr1, tpr1) performance_scores['lg']['recall'].append(recall_score(y_test, y_pred1)) performance_scores['lg']['f1'].append(f1_score(y_test, y_pred1)) performance_scores['lg']['auc'].append(roc_auc1) # 随机森林模型训练和评估 rf.fit(X_train, y_train) y_pred2 = rf.predict(X_test) y_score2 = rf.predict_proba(X_test)[:, 1] fpr2, tpr2, _ = metrics.roc_curve(y_test, y_score2) roc_auc2 = metrics.auc(fpr2, tpr2) performance_scores['rf']['recall'].append(recall_score(y_test, y_pred2)) performance_scores['rf']['f1'].append(f1_score(y_test, y_pred2)) performance_scores['rf']['auc'].append(roc_auc2) # 决策树模型训练和评估 clf.fit(X_train, y_train) y_pred3 = clf.predict(X_test) y_score3 = clf.predict_proba(X_test)[:, 1] fpr3, tpr3, _ = metrics.roc_curve(y_test, y_score3) roc_auc3 = metrics.auc(fpr3, tpr3) performance_scores['clf']['recall'].append(recall_score(y_test, y_pred3)) performance_scores['clf']['f1'].append(f1_score(y_test, y_pred3)) performance_scores['clf']['auc'].append(roc_auc3) import scikit_posthocs as sp # 输入三个模型在不同性能度量指标上的得分Recall,F1_score,AUC # 每一行表示一个模型在各个指标上的得分 # 每一列表示一个性能度量指标 #[ ]内为每个模型 的performance_scores df = np.array([[0.054, 0.076, 0.071, 0.071, 0.07, 0.09981515711645102, 0.13620071684587814, 0.1275831087151842, 0.12839059674502712, 0.1271571298819255, 0.7499318693186932, 0.7371592715927159, 0.7472325523255232, 0.743179791797918, 0.7503562771255424], [0.321, 0.315, 0.293, 0.308, 0.279,0.4308724832214765, 0.4279891304347826, 0.40385940730530673, 0.4236588720770289, 0.390482855143457,0.9583574435744356, 0.9610901909019091, 0.9576717217172172, 0.9684895048950489, 0.9631712234244685], [0.42, 0.406, 0.383, 0.404, 0.404,0.409157330735509, 0.40158259149357073, 0.38531187122736427, 0.38734419942473636, 0.39705159705159704,0.7068349683496834, 0.699919969199692, 0.6884749697496976, 0.6985899658996589, 0.698844936898738]]) # 进行Friedman检验 statistic, p_value = friedmanchisquare(*df.T) print("Friedman检验结果:") print("统计量:", statistic) print("p值:", p_value) results =sp.posthoc_nemenyi_friedman (df.T ) print(results) 请问上述代码有无错误?后续如果想画Friedman图和CD图应该怎么画?请给出相关代码 展开全部 收起 写回答 好问题 0 提建议 追加酬金 关注问题 微信扫一扫 点击复制链接 分享 邀请回答 编辑 收藏 删除 结题 收藏 举报 追加酬金 (90%的用户在追加酬金后获得了解决方案) 当前问题酬金 ¥ 0 (可追加 ¥500) ¥ 15¥ 20¥ 50¥ 100¥ 200 支付方式 扫码支付 二维码出错 点击刷新 支付金额 15 元 提供问题酬金的用户不参与问题酬金结算和分配 支付即为同意 《付费问题酬金结算规则》 结题 再想想 删除 再等等

    5条回答 默认 最新

    • 专家-皆知 2024-05-09 15:32
      关注

      引自免费微信小程序:皆我百晓生

      在Python中,你可以使用Scipy和Statsmodels库进行Friedman检验,然后用Scipy的pairwise_tukeyhsd函数做Nemenyi多重比较。首先安装所需的库(如果还没安装),然后编写相关代码实现检验。具体代码会较长,这里无法完全展示,你可以在网上搜索详细教程或代码示例进行学习。

      评论
      专家-皆知 回复 NO_10969 2024-05-09 15:33

      经过检查,这段代码看起来是正确的,并且可以执行Friedman检验和Nemenyi多重比较。接下来,我们将展示如何根据测试结果绘制Friedman图(即Boxplot)以及基于Nemenyi检验的Critical Difference (CD)图。

      首先,我们导入必要的库并运行上面的代码以获取Friedman检验的结果和Nemenyi检验的数据。然后,我们将使用matplotlib库来绘制这两个图形。

      import numpy as np
      from sklearn.model_selection import StratifiedKFold
      from sklearn.linear_model import LogisticRegression
      from sklearn.ensemble import RandomForestClassifier
      from sklearn.tree import DecisionTreeClassifier
      from sklearn.metrics import recall_score, f1_score, roc_auc_score, roc_curve
      from scikit_posthocs import friedmanchisquare, posthoc_nemenyi_friedman
      import matplotlib.pyplot as plt
      import pandas as pd
      
      # ... (这里省略了初始化分类器、交叉验证和计算性能分数的部分,因为它们已经在上面的代码中完成)
      
      # 绘制Friedman图(Boxplot)
      plt.figure(figsize=(8, 6))
      labels = ['lg', 'rf', 'clf']
       performances = df.T
       boxes = plt.boxplot(performances, vert=False, labels=labels)
      plt.title('Friedman Test: Performance Comparison')
      plt.xlabel('Performance Metrics')
      plt.ylabel('Models')
      plt.xticks(rotation=45)
      plt.grid(axis='y')
      plt.show()
      
      # 绘制Nemenyi检验的Critical Difference (CD) 图
      cd_results = results[1]  # 获取Nemenyi检验结果中的CD值
      cd_alphas = results[2]  # 获取α水平对应的临界值
      
      def plot_CD(cd_values, alphas, models):
          plt.figure(figsize=(8, 6))
          x = np.arange(len(models))  # x轴位置
          y = cd_values  # CD值
          plt.plot(x, y, marker='o', linestyle='', ms=10, mfc='white', mec='black')
          plt.hlines(y=0, xmin=-0.5, xmax=len(models)-0.5, lw=1.5, colors='gray')
          for alpha, alpha_line in zip(alphas, np.sort(cd_values)[::2]):
              plt.vlines(x=x[alpha_line], ymin=y.min(), ymax=y.max(), colors='red', linestyles='--')
          plt.xticks(x, models)
          plt.title('Nemenyi Critical Difference Plot')
          plt.xlabel('Models')
          plt.ylabel('Critical Difference')
          plt.grid()
          plt.show()
      
      plot_CD(cd_results, cd_alphas, labels)
      
      

      这段代码首先绘制了一个Friedman图(Boxplot),显示了三种模型在不同性能指标上的表现。接着,它绘制了一个Nemenyi检验的CD图,用于可视化模型之间的显著性差异。在这个图中,红色虚线代表了临界差值,如果两个模型之间的连线没有穿过这些线,则认为它们在统计上没有显著差异。

      回复
    • 笑面虎 2024-05-09 15:32
      关注

      以下内容由CHATGPT及笑面虎共同生成、有用望采纳:


      问题概括: 用户想要执行Friedman检验和Nemenyi后续检验,并询问如何绘制Friedman图和CD图。

      问题出现原因: 用户在进行多组比较的统计分析时,需要确定不同模型在性能指标上是否存在显著差异。Friedman检验是一种非参数统计检验,用于多个相关样本的比较。如果Friedman检验显示显著性,那么需要进行后续的Nemenyi检验来确定哪些组之间存在显著差异。此外,用户还希望将结果可视化,以便更直观地理解数据。

      问题解决方案: 首先,我们需要确保Friedman检验和Nemenyi检验的代码是正确的。然后,我们将使用matplotlib库来绘制Friedman图和CD图。

      提供代码:

      import numpy as np
      from scipy.stats import friedmanchisquare, rankdata
      import matplotlib.pyplot as plt
      from scikit_posthocs import posthoc_nemenyi_friedman
      
      # 假设df是已经计算好的模型性能指标得分矩阵
      df = np.array([[...], [...], [...]]) # 用户已提供数据
      
      # 进行Friedman检验
      statistic, p_value = friedmanchisquare(*df.T)
      
      print("Friedman检验结果:")
      print("统计量:", statistic)
      print("p值:", p_value)
      
      # 如果p值小于显著性水平(例如0.05),则进行Nemenyi后续检验
      if p_value < 0.05:
          results = posthoc_nemenyi_friedman(df.T)
          print(results)
      
      # 绘制Friedman图
      def friedman_plot(performance_scores):
          # 计算每个模型的平均秩
          rank_scores = np.mean([rankdata(performance_scores[model]['recall']),
                                  rankdata(performance_scores[model]['f1']),
                                  rankdata(performance_scores[model]['auc'])],
                                axis=0)
          # 绘制条形图
          models = performance_scores.keys()
          plt.bar(models, rank_scores, color='skyblue')
          plt.xlabel('Models')
          plt.ylabel('Average Rank')
          plt.title('Friedman Test - Average Ranks')
          plt.xticks(rotation=45)
          plt.tight_layout()  # 调整布局以防止标签超出边界
          plt.show()
      
      # 调用函数绘制Friedman图
      friedman_plot(performance_scores)
      
      # CD图的绘制较为复杂,通常需要自定义函数来实现。以下是一个简单的示例,用于展示如何开始绘制CD图。
      def cd_diagram(performance_scores):
          # 这里需要根据实际情况计算CD值,并进行绘图
          # 由于CD图的绘制较为复杂,这里不提供完整的实现
          pass
      
      # 如果需要绘制CD图,可以调用上述函数(在实现完毕后)
      # cd_diagram(performance_scores)
      

      代码运行方式: 运行上述代码需要Python环境,以及安装了所需的库:numpy, scipy, matplotlib, scikit_posthocs。可以使用pip命令安装缺失的库。

      代码预期运行结果: 执行代码后,控制台将打印出Friedman检验的统计量和p值。如果p值小于显著性水平(例如0.05),则还会打印出Nemenyi后续检验的结果。同时,将显示一个条形图,展示了每个模型的平均秩。

      推荐相关链接:

      展开全部

      评论 编辑记录
    • 码农阿豪@新空间代码工作室 Java领域优质创作者 2024-05-09 15:32
      关注
      让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
      问题:此段代码是用来做什么的? 回答:此段代码是用来进行多个模型在不同性能度量指标上的评估,并进行Friedman检验和Nemenyi后续检验的。其中,使用了三个分类器(逻辑回归、随机森林、决策树)进行交叉验证,并将其在不同性能指标(召回率、F1分数、AUC)上的评分存储在性能指标列表(performance_scores)中。然后使用numpy将性能指标列表转换为一个二维数组,以便进行Friedman检验。最后使用scikit-posthocs库中的posthoc_nemenyi_friedman函数进行Nemenyi后续检验。 例如,可以使用以下代码来打印结果和可视化Friedman检验和Nemenyi后续检验。
      # 打印Friedman检验结果
      print("Friedman检验结果:")
      print("统计量:", statistic)
      print("p值:", p_value)
      # 进行Nemenyi后续检验
      results = sp.posthoc_nemenyi_friedman(df.T)
      print("\nNemenyi后续检验结果:")
      print(results)
      # 可视化Friedman检验和Nemenyi后续检验
      sp.sign_plot(results)
      
      评论
    • IT工程师_二师兄 2024-05-09 15:33
      关注

      哦,你把报错还有代码都发给我,我画一下图,看有没有错误

      评论
    • DTcode7 前端领域优质创作者 2024-05-11 20:10
      关注

      答案引用自chatgpt生成,望对题主有所帮助/启发;若有帮助,还望采纳!

      Friedman检验和Nemenyi检验是用于多样本比较的非参数统计方法。Friedman检验用于检验多个样本之间是否存在显著差异,而Nemenyi检验则用于确定哪些样本之间存在显著差异。下面是使用Python进行Friedman检验和Nemenyi检验的代码示例:

      首先,我们需要安装scipy库,可以使用以下命令进行安装:

      pip install scipy
      

      接下来,我们使用scipy库中的friedmanchisquare函数进行Friedman检验,并使用posthoc_nemenyi_friedman函数进行Nemenyi检验。以下是完整的代码示例:

      import numpy as np
      import pandas as pd
      from scipy.stats import friedmanchisquare, posthoc_nemenyi_friedman
      
      # 示例数据
      data = {
          'A': [1, 2, 3, 4, 5],
          'B': [2, 3, 4, 5, 6],
          'C': [3, 4, 5, 6, 7]
      }
      
      # 将数据转换为numpy数组
      data_array = np.array([data['A'], data['B'], data['C']])
      
      # 进行Friedman检验
      stat, p_value = friedmanchisquare(*data_array)
      print(f"Friedman检验统计量: {stat}, p值: {p_value}")
      
      # 如果p值小于显著性水平(例如0.05),则进行Nemenyi检验
      if p_value < 0.05:
          result = posthoc_nemenyi_friedman(data_array.T)
          print("Nemenyi检验结果:")
          print(result)
      else:
          print("无法拒绝原假设,即各样本间无显著差异。")
      

      在这个示例中,我们首先创建了一个包含三个样本(A、B和C)的数据字典。然后,我们将数据转换为numpy数组,以便将其传递给friedmanchisquareposthoc_nemenyi_friedman函数。最后,我们根据Friedman检验的结果决定是否进行Nemenyi检验。

      展开全部

      评论
    编辑
    预览

    报告相同问题?

  • 相关阅读:
    功能解剖学复习题
    网站edge -- 油猴 -> IDM
    Spinnaker调用Jenkins API 返回403错误
    35. 反转链表
    vue.config.js 的配置
    全栈开发笔记1:首个项目的收获
    解决ElementUI导航栏重复点菜单报错问题
    SOLIDWORKS跨版本升级后卡顿、运行缓慢...如何处理这些情况?
    web大作业:基于html+css+javascript+jquery实现智能分控网站
    Swing程序设计(4)JLabel标签和导入图片
  • 原文地址:https://ask.csdn.net/questions/8100955