python数据分析绘图

news/2024/5/3 16:37:30/文章来源:https://blog.csdn.net/chj65/article/details/128027445

ROC-AUC曲线(分类模型)

混淆矩阵

在这里插入图片描述
混淆矩阵中所包含的信息

  • True negative(TN),称为真阴率,表明实际是负样本预测成负样本的样本数(预测是负样本,预测对了)
  • False positive(FP),称为假阳率,表明实际是负样本预测成正样本的样本数(预测是正样本,预测错了)
  • False negative(FN),称为假阴率,表明实际是正样本预测成负样本的样本数(预测是负样本,预测错了)
  • True positive(TP),称为真阳率,表明实际是正样本预测成正样本的样本数(预测是正样本,预测对了)
    ROC曲线示例
    在这里插入图片描述

可以看到,ROC曲线的纵坐标为真阳率true positive rate(TPR)(也就是recall),横坐标为假阳率false positive rate(FPR)。
TPR即真实正例中对的比例,FPR即真实负例中的错的比例。

  • 真正类率(True Postive Rate)TPR:
    TPR=TP/(TP+FN)
    代表分类器 预测为正类中实际为正实例占所有正实例 的比例。
  • 假正类率(False Postive Rate)FPR:
    FPR=FP/(FP+TN)
    代表分类器 预测为正类中实际为负实例 占 所有负实例 的比例。
    在这里插入图片描述

可以看到,右上角的阈值最小,对应坐标点(1,1);左下角阈值最大,对应坐标点为(0,0)。从右上角到左下角,随着阈值的逐渐减小,越来越多的实例被划分为正类,但是这些正类中同样也掺杂着真正的负实例,即TPR和FPR会同时增大。

  • 横轴FPR: FPR越大,预测正类中实际负类越多。
  • 纵轴TPR:TPR越大,预测正类中实际正类越多。
  • 理想目标:TPR=1,FPR=0,即图中(0,1)点,此时ROC曲线越靠拢(0,1)点,越偏离45度对角线越好。

AUC值是什么?

AUC(Area Under Curve)被定义为ROC曲线下与坐标轴围成的面积,显然这个面积的数值不会大于1。又由于ROC曲线一般都处于y=x这条直线的上方,所以AUC的取值范围在0.5和1之间。

  • AUC越接近1.0,检测方法真实性越高;
  • 等于0.5时,则真实性最低,无应用价值。
    在这里插入图片描述

ROC曲线绘制的代码实现

#导入库
from sklearn.metrics import confusion_matrix,accuracy_score,f1_score,roc_auc_score,recall_score,precision_score,roc_curve
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt#绘制roc曲线   
def calculate_auc(y_test, pred):print("auc:",roc_auc_score(y_test, pred))fpr, tpr, thersholds = roc_curve(y_test, pred)roc_auc = auc(fpr, tpr)plt.plot(fpr, tpr, 'k-', label='ROC (area = {0:.2f})'.format(roc_auc),color='blue', lw=2)plt.xlim([-0.05, 1.05])plt.ylim([-0.05, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('ROC Curve')plt.legend(loc="lower right")plt.plot([0, 1], [0, 1], 'k--')plt.show()

相关性热图

表示数据之间的相互依赖关系。但需要注意,数据具有相关性不一定意味着具有因果关系。

相关系数(Pearson)

相关系数是研究变量之间线性相关程度的指标,而相关关系是一种非确定性的关系,数据具有相关性不能推出有因果关系。相关系数的计算公式如下:
在这里插入图片描述
其中,公式的分子为X,Y两个变量的协方差,Var(X)和Var(Y)分别是这两个变量的方差。当X,Y的相关程度最高时,即X,Y趋近相同时,很容易发现分子和分母相同,即r=1。

代码实现

相关性计算
import numpy as np
import pandas as pd
# compute correlations
from scipy.stats import spearmanr, pearsonr
from scipy.spatial.distance import cdistdef calc_spearman(df1, df2):df1 = pd.DataFrame(df1)df2 = pd.DataFrame(df2)n1 = df1.shape[1]n2 = df2.shape[1]corr0, pval0 = spearmanr(df1.values, df2.values)# (n1 + n2) x (n1 + n2)corr = pd.DataFrame(corr0[:n1, -n2:], index=df1.columns, columns=df2.columns)pval = pd.DataFrame(pval0[:n1, -n2:], index=df1.columns, columns=df2.columns)return corr, pvaldef calc_pearson(df1, df2):df1 = pd.DataFrame(df1)df2 = pd.DataFrame(df2)n1 = df1.shape[1]n2 = df2.shape[1]corr0, pval0 = np.zeros((n1, n2)), np.zeros((n1, n2))for row in range(n1):for col in range(n2):_corr, _p = pearsonr(df1.values[:, row], df2.values[:, col])corr0[row, col] = _corrpval0[row, col] = _p# n1 x n2corr = pd.DataFrame(corr0, index=df1.columns, columns=df2.columns)pval = pd.DataFrame(pval0, index=df1.columns, columns=df2.columns)return corr, pval
画出相关性图
import matplotlib.pyplot as plt
import seaborn as snsdef pvalue_marker(pval, corr=None, only_pos=False):if only_pos:  # 只标记正相关if corr is None:  print('correlations `corr` is not provided, ''negative correlations cannot be filtered!')else:pval = pval + (corr < 0).astype(float)pval_marker = pval.applymap(lambda x: '**' if x < 0.01 else ('*' if x < 0.05 else ''))return pval_markerdef plot_heatmap(mat, cmap='RdBu_r', xlabel=f'column', ylabel=f'row',tt='',fp=None,**kwds
):fig, ax = plt.subplots()sns.heatmap(mat, ax=ax, cmap=cmap, cbar_kws={'shrink': 0.5}, **kwds)ax.set_title(tt)ax.set_xlabel(xlabel)ax.set_ylabel(ylabel)if fp is not None:ax.figure.savefig(fp, bbox_inches='tight')return ax

实例

#构造有一定相关性的随机矩阵
df1 = pd.DataFrame(np.random.randn(40, 9))
df2 = df1.iloc[:, :-1] + df1.iloc[:, 1: ].values * 0.6
df2 += 0.2 * np.random.randn(*df2.shape)
#绘图
corr, pval = calc_pearson(df1, df2)
pval_marker = pvalue_marker(pval, corr, only_pos=only_pos)
tt = 'Spearman correlations'
plot_heatmap(corr, xlabel='df2', ylabel='df1',tt=tt, cmap='RdBu_r', #vmax=0.75, vmin=-0.1,annot=pval_marker, fmt='s',
)

在这里插入图片描述
only_pos 这个参数为 False 时, 会同时标记显著的正相关和负相关.
cmap属性调整颜色可选参数:

‘Accent’, ‘Accent_r’, ‘Blues’, ‘Blues_r’, ‘BrBG’, ‘BrBG_r’, ‘BuGn’, ‘BuGn_r’, ‘BuPu’, ‘BuPu_r’, ‘CMRmap’,‘CMRmap_r’, ‘Dark2’, ‘Dark2_r’, ‘GnBu’, ‘GnBu_r’, ‘Greens’, ‘Greens_r’, ‘Greys’, ‘Greys_r’, ‘OrRd’, ‘OrRd_r’, ‘Oranges’, ‘Oranges_r’, ‘PRGn’, ‘PRGn_r’, ‘Paired’, ‘Paired_r’, ‘Pastel1’, ‘Pastel1_r’, ‘Pastel2’, ‘Pastel2_r’, ‘PiYG’, ‘PiYG_r’, ‘PuBu’, ‘PuBuGn’, ‘PuBuGn_r’, ‘PuBu_r’, ‘PuOr’, ‘PuOr_r’, ‘PuRd’, ‘PuRd_r’, ‘Purples’, ‘Purples_r’, ‘RdBu’, ‘RdBu_r’, ‘RdGy’, ‘RdGy_r’, ‘RdPu’, ‘RdPu_r’, ‘RdYlBu’, ‘RdYlBu_r’, ‘RdYlGn’, ‘RdYlGn_r’, ‘Reds’, ‘Reds_r’, ‘Set1’, ‘Set1_r’, ‘Set2’, ‘Set2_r’, ‘Set3’, ‘Set3_r’, ‘Spectral’, ‘Spectral_r’, ‘Wistia’, ‘Wistia_r’, ‘YlGn’, ‘YlGnBu’, ‘YlGnBu_r’, ‘YlGn_r’, ‘YlOrBr’, ‘YlOrBr_r’, ‘YlOrRd’, ‘YlOrRd_r’, ‘afmhot’, ‘afmhot_r’, ‘autumn’, ‘autumn_r’, ‘binary’, ‘binary_r’,‘bone’, ‘bone_r’, ‘brg’, ‘brg_r’, ‘bwr’, ‘bwr_r’, ‘cividis’, ‘cividis_r’, ‘cool’, ‘cool_r’, ‘coolwarm’, ‘coolwarm_r’, ‘copper’, ‘copper_r’, ‘crest’, ‘crest_r’, ‘cubehelix’, ‘cubehelix_r’, ‘flag’, ‘flag_r’, ‘flare’, ‘flare_r’, ‘gist_earth’, ‘gist_earth_r’, ‘gist_gray’, ‘gist_gray_r’, ‘gist_heat’, ‘gist_heat_r’, ‘gist_ncar’, ‘gist_ncar_r’, ‘gist_rainbow’, ‘gist_rainbow_r’, ‘gist_stern’, ‘gist_stern_r’, ‘gist_yarg’, ‘gist_yarg_r’, ‘gnuplot’, ‘gnuplot2’, ‘gnuplot2_r’, ‘gnuplot_r’, ‘gray’, ‘gray_r’, ‘hot’, ‘hot_r’, ‘hsv’, ‘hsv_r’,‘plasma’, ‘plasma_r’, ‘prism’, ‘prism_r’, ‘rainbow’, ‘rainbow_r’, ‘rocket’, ‘rocket_r’, ‘seismic’, ‘seismic_r’, ‘spring’, ‘spring_r’, ‘summer’, ‘summer_r’, ‘tab10’, ‘tab10_r’, ‘tab20’, ‘tab20_r’, ‘tab20b’, ‘tab20b_r’, ‘tab20c’, ‘tab20c_r’, ‘terrain’, ‘terrain_r’, ‘turbo’, ‘turbo_r’, ‘twilight’, ‘twilight_r’, ‘twilight_shifted’, ‘twilight_shifted_r’, ‘viridis’, ‘viridis_r’, ‘vlag’, ‘vlag_r’, ‘winter’, ‘winter_r’

棒棒糖图

条形图在数据可视化里,是一个经常被使用到的图表。虽然很好用,也还是存在着缺陷呢。比如条形图条目太多时,会显得臃肿,不够直观。
棒棒糖图表则是对条形图的改进,以一种小清新的设计,清晰明了表达了我们的数据。

代码实现
# 导包
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd# 创建数据
x=range(1,41)
values=np.random.uniform(size=40)
# 绘制
plt.stem(x, values)
plt.ylim(0, 1.2)
plt.show()

在这里插入图片描述

# stem function: If x is not provided, a sequence of numbers is created by python:
plt.stem(values)
plt.show()

在这里插入图片描述

# Create a dataframe
df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'values':np.random.uniform(size=20) })# Reorder it based on the values:
ordered_df = df.sort_values(by='values')
my_range=range(1,len(df.index)+1)
ordered_df.head()
# Make the plot
plt.stem(ordered_df['values'])
plt.xticks( my_range, ordered_df['group'])
plt.show()

在这里插入图片描述

# Horizontal version
plt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')
plt.plot(ordered_df['values'], my_range, "D")plt.yticks(my_range, ordered_df['group'])
plt.show()

在这里插入图片描述

# change color and shape and size and edges
(markers, stemlines, baseline) = plt.stem(values)
plt.setp(markers, marker='D', markersize=10, markeredgecolor="orange", markeredgewidth=2)
plt.show()

在这里插入图片描述

# custom the stem lines
(markers, stemlines, baseline) = plt.stem(values)
plt.setp(stemlines, linestyle="-", color="olive", linewidth=0.5 )
plt.show()

在这里插入图片描述

# Create a dataframe
value1=np.random.uniform(size=20)
value2=value1+np.random.uniform(size=20)/4
df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'value1':value1 , 'value2':value2 })# Reorder it following the values of the first value:
ordered_df = df.sort_values(by='value1')
my_range=range(1,len(df.index)+1)
# The horizontal plot is made using the hline function
plt.hlines(y=my_range, xmin=ordered_df['value1'], xmax=ordered_df['value2'], color='grey', alpha=0.4)
plt.scatter(ordered_df['value1'], my_range, color='skyblue', alpha=1, label='value1')
plt.scatter(ordered_df['value2'], my_range, color='green', alpha=0.4 , label='value2')
plt.legend()# Add title and axis names
plt.yticks(my_range, ordered_df['group'])
plt.title("Comparison of the value 1 and the value 2", loc='left')
plt.xlabel('Value of the variables')
plt.ylabel('Group')# Show the graph
plt.show()

在这里插入图片描述

# Data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x) + np.random.uniform(size=len(x)) - 0.2# Create a color if the y axis value is equal or greater than 0
my_color = np.where(y>=0, 'orange', 'skyblue')
# The vertical plot is made using the vline function
plt.vlines(x=x, ymin=0, ymax=y, color=my_color, alpha=0.4)
plt.scatter(x, y, color=my_color, s=1, alpha=1)# Add title and axis names
plt.title("Evolution of the value of ...", loc='left')
plt.xlabel('Value of the variable')
plt.ylabel('Group')# Show the graph
plt.show()

在这里插入图片描述

火山图

火山图(Volcano plots)是散点图的一种,根据变化幅度(FC,Fold Change)和变化幅度的显著性(P value)进行绘制,其中标准化后的FC值作为横坐标,P值作为纵坐标,可直观的反应高变的数据点,常用于基因组学分析(转录组学、代谢组学等)。

绘制

制作差异分析结果数据框

genearray = np.asarray(pvalue)result = pd.DataFrame({'pvalue':genearray,'FoldChange':fold})result['log(pvalue)'] = -np.log10(result['pvalue'])

制作火山图的准备工作

result['sig'] = 'normal'result['size']  =np.abs(result['FoldChange'])/10result.loc[(result.FoldChange> 1 )&(result.pvalue < 0.05),'sig'] = 'up'
result.loc[(result.FoldChange< -1 )&(result.pvalue < 0.05),'sig'] = 'down'
ax = sns.scatterplot(x="FoldChange", y="log(pvalue)",hue='sig',hue_order = ('down','normal','up'),palette=("#377EB8","grey","#E41A1C"),data=result)
ax.set_ylabel('-log(pvalue)',fontweight='bold')
ax.set_xlabel('FoldChange',fontweight='bold')

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_37048.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

activiti-bpmn-converter

activiti-bpmn-converter目录概述需求&#xff1a;设计思路实现思路分析1.BpmnXMLConstants2.BpmnXMLConverter3.StartEventXMLConverter4.EndEventXMLConverter参考资料和推荐阅读Survive by day and develop by night. talk for import biz , show your perfect code,full bu…

伸展树原理介绍

一 点睛 伸展树&#xff0c;也叫作分裂树&#xff0c;是一种二叉搜索树&#xff0c;可以在 O (logn ) 内完成插入、查找和删除操作。在任意数据结构的生命周期内执行不同操作的概率往往极不均衡&#xff0c;而且各操作之间有极强的相关性&#xff0c;在整体上多呈现极强的规律…

zabbix集群搭建分布式监控的操作步骤

作用&#xff1a; 分担server的集中式压力解决多机房之间的网络延迟问题环境准备&#xff1a; 服务器1&#xff1a;zabbix-server 服务器2&#xff1a;zabbix-proxy 服务器3&#xff1a;zabbix-agent 关系&#xff1a;zabbix-agent发送数据到代理&#xff0c;代理汇总数据发送…

学习Python要学习哪些课程?

通过学习 Python数据分析与应用课程&#xff0c;可以掌握Python进行科学计算、可视化绘图、数据处理&#xff0c;分析与建模、构建聚类、回归、分类模型的主要方法和技能&#xff0c;并为后续相关课程学习及将来从事数据分析挖掘研究、数据分析工作奠定基础。 Python数据分析与…

XSStrike工具使用说明

今天继续给大家介绍渗透测试相关知识&#xff0c;本文主要内容是XSStrike工具使用说明。 免责声明&#xff1a; 本文所介绍的内容仅做学习交流使用&#xff0c;严禁利用文中技术进行非法行为&#xff0c;否则造成一切严重后果自负&#xff01; 再次强调&#xff1a;严禁对未授权…

记录:微星 GE63 屏轴断裂 之后。。。

2022/11/25 记录 微星 GE63 1070 笔记本&#xff0c;使用的第三年&#xff0c;已过保了一年&#xff0c;上周使用时&#xff0c;准备合上笔记本盖。啪一下&#xff0c;左侧屏轴断裂&#xff0c;B面翘起&#xff0c;A面左下角轴盖断了一截。 网上好多人都有类似的情况&#xff…

Linux多核运行机制(SMP)

一、Linux内核兼容多处理器要求 有多个 CPU 处理器 的 系统中 , Linux 内核需要处理的问题 : 1、公平共享 : CPU 的负载 , 需要公平地共享 , 不能出现某个CPU空闲 , 造成资源浪费。 2、可设置进程 与 CPU 亲和性 : 可以为 某些类型的 进程 与 指定的 处理器设置亲和性 , 可以针…

数据结构与算法之让我们种下一棵字典树(Java/C++双语言实现)

⭐️前面的话⭐️ 本篇文章将介绍一种经常使用的数据结构——字典树&#xff0c;它又称Tire树&#xff0c;前缀树&#xff0c;字典树&#xff0c;顾名思义&#xff0c;是关于“字典”的一棵树。这个词典中的每个“单词”就是从根节点出发一直到某一个目标节点的路径&#xff0…

CSRF漏洞简介

今天继续给大家介绍渗透测试相关知识&#xff0c;本文主要内容是CSRF漏洞原理、产生与危害。 免责声明&#xff1a; 本文所介绍的内容仅做学习交流使用&#xff0c;严禁利用文中技术进行非法行为&#xff0c;否则造成一切严重后果自负&#xff01; 再次强调&#xff1a;严禁对未…

C语言 * 数组的解析 *

目录 一&#xff1a;一维数组的创建和初始化 1.1 数组的创建 1.2 数组的初始化 1.3 一维数组的使用 1.4 一维数组在内存中的存储 二&#xff1a;二维数组的创建和初始化 2.1 数组的创建 2.2 数组的初始化 2.3 一维数组的使用 2.4 一维数组在内存中的存储 2.5 数组越…

【蓝桥杯选拔赛真题30】python计算倒数和 青少年组蓝桥杯python 选拔赛STEMA比赛真题解析

目录 python计算倒数和 一、题目要求 1、编程实现 2、输入输出 3、评分标准

从01背包说起(上)

目录 引入 1.什么是动态规划? 2.什么是背包问题&#xff1f; 3.什么是01背包&#xff1f; 模板题 1.题面 2.思路 Ⅰ为何不可用贪心 Ⅱ状态转移方程 3.代码 下期预告 引入 1.什么是动态规划? 动态规划&#xff08;英语&#xff1a;Dynamic programming&#xff0…

收到多个20k+的offer!选哪一个呢?

“收到offer了&#xff01;”最近&#xff0c;黑马老师收到最多的消息就属这句了。随着黑马各个学科迎来毕业&#xff0c;班主任收到的喜讯越来越多。班主任说&#xff0c;没有比在接近年底时收到学生就业喜讯更让人开心的事了。今天&#xff0c;播妞给大家带来的是黑马HTML&am…

就两秒?这说出去谁信啊!

文 | xiaoyi&#xff08;转载请后台联系&#xff09;关注公众号&#xff1a;小一的学习笔记截止发文&#xff0c;北上广深一共有6510条公交线路为了获取上面的这些线路信息&#xff0c;我写了一个爬虫&#xff0c;大概用了2秒左右就搞定&#xff0c;真爽&#xff01;说出来你们…

【项目实战:核酸检测平台】第三章 利其器

第三章 利其器 摘要:俗话说的好工欲善其事&#xff0c;必先利其器&#xff0c;框架搭的好&#xff0c;开发起来很舒服&#xff0c;搭的不好&#xff0c;开发起来就很痛苦。 一个程序员只会写业务代码&#xff0c;最多算是个码农&#xff0c;搭框架的本事、遇到难题的解决能力…

第八章 兼容多种模块标准的软件包封装

第八章 如何封装兼容多种JS模块标准的软件包&#xff1f; 为了方便用户使用&#xff0c;一款成熟的类库都会提供多种模块封装形式&#xff0c;比如大家最常用到的 Vue&#xff0c;就提供了cjs、esm、umd 等多种封装模式&#xff0c;并且还会提供对应的压缩版本&#xff0c;方便…

微服务之间,最佳的调用方式是什么?

在微服务架构中&#xff0c;需要调用很多服务才能完成一项功能。服务之间如何互相调用就变成微服务架构中的一个关键问题。服务调用有两种方式&#xff0c;一种是RPC方式&#xff0c;另一种是事件驱动&#xff08;Event-driven&#xff09;方式&#xff0c;也就是发消息方式。消…

MySQL海量数据优化(理论+实战) 吊打面试官

一、准备表数据 咱们建一张用户表&#xff0c;表中的字段有用户ID、用户名、地址、记录创建时间&#xff0c;如图所示 ​OK&#xff0c;接下来准备写一个存储过程插入一百万条数据 CREATE TABLE t_user (id int NOT NULL,user_name varchar(32) CHARACTER SET utf8 COLLATE ut…

2023最新SSM计算机毕业设计选题大全(附源码+LW)之java线上学习系统8e88w

做毕业设计一定要选好题目。毕设想简单&#xff0c;其实很简单。这里给几点建议&#xff1a; 1&#xff1a;首先&#xff0c;学会收集整理&#xff0c;年年专业都一样&#xff0c;岁岁毕业人不同。很多人在做毕业设计的时候&#xff0c;都犯了一个错误&#xff0c;那就是不借鉴…

路由策略和路由控制

路由策略和路由控制 路由策略 针对路由的发布&#xff0c;接收&#xff0c;引入进行控制&#xff0c;从而影响数据的路径或者可达性 路由匹配工具 ACL&#xff1a;访问前缀列表 一个ACL用多条规则组成&#xff0c;不同规则之间通过rule id进行区分&#xff0c;默认rule 步…