如何通过在Python中通过热图相减来显示两个矩阵的差异? [英] How can display differences of two matrices by subtraction via heatmap in python?

查看:307
本文介绍了如何通过在Python中通过热图相减来显示两个矩阵的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵[A](Expected_matrice),[B](Predicted_matrice)我需要通过减去三个[C]创建第三个[C](Error_matrice)并将其传递给Pandas数据帧并保存在csv中文件.

I have two matrices [A](Expected_matrice) , [B](Predicted_matrice) I need to create the third one [C](Error_matrice) via subtraction of them [C]=[A]-[B] and pass it to Pandas dataframe and save in csv file.

由于上述矩阵的大小为24 * 20,因此我尝试:

Since abovementioned matrices' size are 24*20 and I try to:

首先:通过sns.heatmap(C, cbar=True, cmap="gray_gist")

第二:评估 [C],方法是应用sum(abs(abs([A])-abs([B])))/24*20来检查其效果如何.实际上,我以此计算错误的数量.我也知道,可以通过应用以下方法使用其他方法,例如MSE from Sklearn import metrics:

Second: Evaluate [C] via applying sum(abs(abs([A])-abs([B])))/24*20 to check that how good it is. In fact I calculating amount of Error by that. I also know that it's possible to use another method like MSE from Sklearn import metrics by applying:

from Sklearn import metrics
print(metrics.mean_squared_error(A,B))

由于矩阵的元素是列表,因此我使用过:[i - j for (i, j) in zip(A,B)]

Since the elements of matrices are lists I've used : [i - j for (i, j) in zip(A,B)]

我的代码如下:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter

#A,B can be read from .csv files
A = pd.read_csv('D:\A.csv', header=None)
B = pd.read_csv('D:\B.csv', header=None)

#A,B can be assumed as lists
df_A = pd.DataFrame(A)
df_B = pd.DataFrame(B)

#calculate error matrix via subtraction 
C = [i - j for (i, j) in zip(A,B)]

#Pass error matrix to Pandas dataframe
df_C = pd.DataFrame(C)
df_C.to_csv('Error_Matrix.csv', header=None, index=None)

#Evaluation
Eval= sum(abs(abs([A])-abs([B])))/24*20
Eval_ =  '{:04}'.format(Eval)
print(Eval_)

#Plotting C
fig, ax = plt.subplots(nrows=1, ncols=2 , figsize=(20,15))

plt.subplot(1,2,1)
ax = sns.heatmap(C, cbar=True, cmap="gist_gray")
plt.title(f'Error Matrix  Error={Eval_}', fontsize=14 , fontweight='bold', color='black', loc='center', style='italic')
plt.axis('off')

plt.subplot(1,2,2)
C_smooth = gaussian_filter(dfr_b, sigma=1)
ax = sns.heatmap(C_smooth, vmin=np.min(C_smooth), vmax=np.max(C_smooth), cmap ="gray" , cbar=True , cbar_kws={"ticks":[0,33,67,100]})
plt.title(f'Error Matrix Smooth  Error={Eval_}', fontsize=14 , fontweight='bold', color='black', loc='center', style='italic')
plt.axis('off')
plt.savefig('Error_Matrix.png') 
plt.show()

预期结果:

注意,白色显示Error = 0,纯黑色显示Error = maxum. 大多数情况下应该是错误的,但是我不想得到黑色的结果,我主要希望使用灰色.

Note white color shows Error=0 and solid black color shows Error=maximum. Mostly should be error but i don't want to have black result I expected Gray color mostly.

数据(矩阵A,B):矩阵A 矩阵B

推荐答案

我会做这样的事情:

import matplotlib.pyplot as plt
import numpy as np


mx = 10 + 3 * np.random.random( 20 * 10 )
mx = mx.reshape( 20, 10 )
nx = 10 + 3 * np.random.random( 20 * 10 )
nx = nx.reshape( 20, 10 )
deltax = mx - nx
ox = 100 * ( 1 - np.abs( ( deltax) / mx ) )

scale = max( [ abs(min( np.concatenate( deltax ) ) ), abs( max( np.concatenate( deltax ) ) ) ] )

chi2 = np.sum( mx - nx )**2
chi2Red = chi2/( len( mx ) * len( mx[0] ) )
print chi2, chi2Red

fig = plt.figure()
ax = fig.add_subplot( 2, 2, 1 )
bx = fig.add_subplot( 2, 2, 2 )
cx = fig.add_subplot( 2, 2, 3 )
dx = fig.add_subplot( 2, 2, 4 )

MX1 = ax.matshow( mx, vmin=0, vmax=30 )
MX2 = bx.matshow( nx, vmin=0, vmax=30 )
diffMX = cx.matshow( deltax, cmap='seismic', vmin=-scale, vmax=scale )
errMX = dx.matshow( ox, vmin=0, vmax=100  )
plt.colorbar( MX1, ax=ax )
plt.colorbar( MX2, ax=bx )
plt.colorbar( diffMX, ax=cx )
plt.colorbar( errMX, ax=dx )
plt.show()

给予:

>> 219.40945851846487 1.0970472925923245

我不得不说,我不喜欢失去有关偏差迹象的信息.因此,左下图将是我的实际偏好.它可以像最后一个一样缩放和移动,以使零变为100%,数据范围从80%到120%或类似程度.

I have to say though, that I do not like loosing the information about the sign of deviation. The lower left graph, hence, would be my actual preference. It could be scaled and shifted like the last one such that zero becomes 100% and the data will range from 80% to 120% or somewhat like that.

这篇关于如何通过在Python中通过热图相减来显示两个矩阵的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆