zl程序教程

您现在的位置是:首页 >  其它

当前栏目

相关性分析你了解多少?可视化展示一下吧~~

分析 了解 可视化 多少 展示 一下 相关性
2023-06-13 09:13:56 时间

今天小编介绍数据分析中最常用的方法之一相关性分析,该步骤多用于数据探索过程中,用于检测数据维度之间的相关密切程度。本文将通过以下内容介绍相关性分析:

  • 相关性定义及种类
  • 相关性分析图表展示

相关性分析简介

基本介绍

相关性分析常用于对不同特征或数据集不同维度中相关程度的分析,通过分析不同特征与目标变量之间相关性程度,可发现业务运营中的关键因素。而在数据建模任务中,相关性分析也是特征选择中数据维度共线性分析测试的重要一环。

相关性可简单的分为正相关、负相关和不相关,当然也有相关性程度的强弱之分,可视化图表表示如下:

相关性示意图(来源网路)

在数据运营过程中,常因为数据集多个自变量之间存在较高的相关性而导致共线性问题,进而导致以此数据建立的模型稳定性和准确度降低。如何有效判定数据维度间的共线性问题,可以从以下几个方面进行介绍:

  • 容忍度(Tolerance):值介于0和1之间,值越小,存在共线性的可能就越大。
  • 方差膨胀因子:容忍度的倒数,通常以10作为标准,大于10则存在明显的多重共线性问题。
  • 特征值:PCA分析中的结果之一,如多个维度的特征值为0,则可能存在共线性。
  • 相关系数R:常规的方法之一,当R大于0.8时,表示有较强的正相关性。

(以上简单介绍一下相关性分析的模型构建拓展,感兴趣的可自行查阅。)

相关系数、判定系数、回归系数

相关系数、判定系数、回归系数 好多小伙伴不太理解,这里小编就简单介绍一下,如下:

  • 相关系数:衡量变量间相关程度的指标,常用R表示。
  • 判定系数:是相关系数R的平方,是自变量对因变量的方差解释程度的参考值。
  • 回归系数:是回归方程中表示自变量X对因变量Y影响大小的参数。

当回归系数>0时,相关系数在(0,1)之间,则表明二者正相关,若回归系数<0,相关系数在(-1,0)之间,说明二者负相关。

以上就是小编关于相关性及关键评价指标的简单介绍,更多详细内容,小伙伴们可自行搜索哈~

相关性图表绘制

这一部分,小编将分别使用Python、R绘制一个具体学术相关性散点图。详细内容如下:

Python绘制

test_data = pd.read_excel('scatter_plot_data.xlsx')


import pandas as pd
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error,r2_score
from matplotlib.pyplot import MultipleLocator
from scipy.stats import linregress  
#统一修改字体
plt.rcParams['font.family'] = ['Times New Roman']

test_data = pd.read_excel('scatter_plot_data.xlsx')

N = len(test_data['true_data'])
x = test_data['true_data'].values.ravel() #真实值
y = test_data['model01_estimated'].values.ravel()#预测值
C=round(r2_score(x,y),4)
rmse = round(np.sqrt(mean_squared_error(x,y)),3)
#绘制拟合线
x2 = np.linspace(-10,10)
y2=x2
def f_1(x, A, B):  
    return A*x + B  
A1, B1 = optimize.curve_fit(f_1, x, y)[0]  
y3 = A1*x + B1

#绘制误差线数据点
up_y2 = 1.15*x2 + 0.05
down_y2 = 0.85*x2 - 0.05

#绘制误差线数据点
up_y2 = 1.15*x2 + 0.05
down_y2 = 0.85*x2 - 0.05

line_01 = linregress(x2,y2)
line_top = linregress(x2,up_y2)
line_bopptom = linregress(x2,down_y2)

# 统计计算所得
all_data = 4348
top_counts = 1681
bottom_counts = 404
bottom_top_counts = 2263

#开始绘图
fig, ax = plt.subplots(figsize=(7,5),dpi=200)
ax.scatter(x, y,edgecolor=None, c='k', s=12,marker='s')
ax.plot(x2,y2,color='k',linewidth=1.5,linestyle='-',zorder=2)
ax.plot(x,y3,color='r',linewidth=2,linestyle='-',zorder=2)

#添加上线和下线
ax.plot(x2,up_y2,color='k',lw=1.,ls='--',zorder=2,alpha=.8)
ax.plot(x2,down_y2,color='k',lw=1.,ls='--',zorder=2,alpha=.8)
fontdict1 = {"size":17,"color":"k",}
ax.set_xlabel("True Values", fontdict=fontdict1)
ax.set_ylabel("Estimated Values ", fontdict=fontdict1)
ax.grid(which='major',axis='y',ls='--',c='k',alpha=.7)
ax.set_axisbelow(True)
ax.set_xlim((0, 2.0))
ax.set_ylim((0, 2.0))
ax.set_xticks(np.arange(0, 2.2, step=0.2))
ax.set_yticks(np.arange(0, 2.2, step=0.2))



for spine in ['top','left','right']:
    ax.spines[spine].set_visible(None)
ax.spines['bottom'].set_color('k')
ax.tick_params(bottom=True,direction='out',labelsize=14,width=1.5,length=4,
              left=False)
#ax.tick_params()
#添加题目
titlefontdict = {"size":20,"color":"k",}
ax.set_title('Scatter plot of Correlation Analysis',titlefontdict,pad=20)
#ax.set_title()
fontdict = {"size":16,"color":"k"}
ax.text(0.1,1.8,r'$R^2=$'+str(round(C,3)),fontdict=fontdict)
ax.text(0.1,1.6,"RMSE="+str(rmse),fontdict=fontdict)
ax.text(0.1,1.4,r'$y=$'+str(round(A1,3))+'$x$'+" + "+str(round(B1,3)),fontdict=fontdict)
ax.text(0.1,1.2,r'$N=$'+ str(N),fontdict=fontdict)

#添加上下线的统计个数
text_font = {'size':'16','weight':'medium','color':'black'}
label_font = {'size':'24','weight':'medium','color':'black'}
ax.text(.9,.9,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)

ax.text(.7,.25,s='Within EE = ' + '{:.0%}'.format(bottom_top_counts/all_data),transform = ax.transAxes,
        ha='left', va='center',fontdict=text_font)
ax.text(.7,.18,s='Above EE = ' + '{:.0%}'.format(top_counts/all_data),transform = ax.transAxes,
        ha='left', va='center',fontdict=text_font)
ax.text(.7,.11,s='Below EE = ' + '{:.0%}'.format(bottom_counts/all_data),transform = ax.transAxes,
        ha='left', va='center',fontdict=text_font)

ax.text(.8,.056,'\nVisualization by DataCharm',transform = ax.transAxes,
        ha='center', va='center',fontsize = 10,color='black')
plt.show()

Example Chart Of Correlation Analysis in Python

更多绘制细节可参考Python-matplotlib 学术散点图 EE 统计及绘制

R绘制

R-ggplot2绘制小编这里也直接给出绘制代码。如下:

library(tidyverse)
scatter_data <- read.csv('scatter_ggplot2.csv')

#可视化绘制
ggplot(scatter_data,aes(x = true_data,y = model01_estimated)) +
  geom_point(shape=15) + 
  geom_smooth(method = 'lm',se = F,color='red',size=1) +
  #绘制对角线:最佳拟合线
  geom_abline(slope = 1,intercept = 0,color='black',size=1) +
  #绘制上误差线
  geom_abline(slope = 1.15,intercept = .05,linetype = "dashed",size=1) +
  #绘制下误差线
  geom_abline(slope = .85,intercept = -.05,linetype = "dashed",size=1) +
  #使用 ggpubr 包添加R2等元素
  stat_regline_equation(label.x = .1,label.y = 1.8,size=6,family='Times_New_Roman',fontface='bold')+
  stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
      label.x = .1, label.y = 1.6,size=6,family='Times_New_Roman',fontface='bold') +
  geom_text(x=.1,y=1.4,label="N = 4348",size=6,family='Times_New_Roman',hjust = 0)+
  #修改坐标轴刻度
  scale_x_continuous(limits = c(0,2),breaks = seq(0,2,0.2),expand = c(0,0)) +
  scale_y_continuous(limits = c(0,2),breaks = seq(0,2,0.2),expand = c(0,0)) +
  labs(x ='True Values',y="Model Estimated",
       title = "The scatter chart of Train data and Tset data",
       subtitle = "scatter R-ggplot2 Exercise(no color)",
       caption = 'Visualization by DataCharm')+
  #添加图序号(a)
  geom_text(x=1.85,y=1.85,label='(a)',size=9,family='Times_New_Roman',fontface='bold')+
  #添加误差个数
  geom_text(x=1.4,y=.4,label='Within EE = 52%',size=5,family='Times_New_Roman',hjust = 0)+
  geom_text(x=1.4,y=.3,label='Above EE = 39%',size=5,family='Times_New_Roman',hjust = 0)+
  geom_text(x=1.4,y=.2,label='Below EE = 9%',size=5,family='Times_New_Roman',hjust = 0)+
  #theme_base() +
  theme(text = element_text(family = "Times_New_Roman",face='bold'),
           axis.text = element_text(family = 'Times_New_Roman',size = 12,face = 'bold'),
           #修改刻度线内
           axis.ticks.length=unit(0.22, "cm"), 
           #绘制虚线网格
           panel.grid.major.y = element_line(linetype = 'dotted',color = 'black'),
           #去除y刻度
           axis.ticks.y = element_blank(),
           axis.line.y = element_blank(),
           #去除panel 背景颜色
           panel.background = element_rect(fill = NA),
           panel.ontop = F,
           #加宽图边框
           #panel.border = element_rect(size=1),
           plot.background = element_rect(fill = NULL),
           axis.line = element_line(size = .8),
           axis.ticks = element_line(size = .8),
           #设置刻度label的边距
           axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")), 
           axis.text.y = element_text(margin=unit(c(0.3,0.3,0.3,0.3), "cm")))

Example Chart Of Correlation Analysis in R

更多绘制细节可参考R-ggplot2 学术散点图绘制

总结

今天这篇推文,小编简单的介绍了相关性含义,并分别使用PythonR语言进行了一个标准相关性散点图的绘制,希望可以给需要的小伙伴一些帮助~~