文字attention矩陣視覺化

2021-09-10 06:43:27 字數 2720 閱讀 4189

在機器閱讀理解的**中,經常可以看到對「文章-問題」視覺化的二維熱力圖,例如下圖。在看實驗結果的時候用這種圖可以直觀的看到attention的效果怎麼樣。比如下圖:

於是從github中找到了乙個例子,進行了簡單的實驗。

import numpy as np

import matplotlib.pyplot as plt

import pandas as pd

import matplotlib.ticker as ticker

a = torch.randn(4, 2)

b = a.softmax(dim=1)

c = a.softmax(dim=0).transpose(0, 1)

print(a, '\n', b, '\n', c)

d = b.matmul(c)

print(d)

d = d.numpy()

得到numpy的4*4資料。然後用matplotlib視覺化。

variables = ['a','b','c','x']

labels = ['id_0','id_1','id_2','id_3']

df = pd.dataframe(d, columns=variables, index=labels)

fig = plt.figure()

ax = fig.add_subplot(111)

cax = ax.matshow(df, interpolation='nearest', cmap='hot_r')

fig.colorbar(cax)

tick_spacing = 1

ax.xaxis.set_major_locator(ticker.multiplelocator(tick_spacing))

ax.yaxis.set_major_locator(ticker.multiplelocator(tick_spacing))

ax.set_xticklabels([''] + list(df.columns))

ax.set_yticklabels([''] + list(df.index))

plt.show()

得到下圖:

如何把文字顯示到座標軸上:

nlp = spacy.load('en')    #import spacy,用於分詞

sent = nlp('which nfl team represented the afc at super bowl 50') #對文章提乙個問題

doc = open('f:/spacy.txt').read()

doc = nlp(doc)

data =

for token1 in doc:

d = np.array(data)

d = d.transpose()

col = [t.text for t in doc] #需要顯示的詞

index = [t.text for t in sent] #需要顯示的詞

df = pd.dataframe(d, columns=col, index=index )

fig = plt.figure()

ax = fig.add_subplot(111)

cax = ax.matshow(df, interpolation='nearest', cmap='hot_r')

#cax = ax.matshow(df)

fig.colorbar(cax)

tick_spacing = 1

ax.xaxis.set_major_locator(ticker.multiplelocator(tick_spacing))

ax.yaxis.set_major_locator(ticker.multiplelocator(tick_spacing))

# fontdict = #設定文字旋轉

fontdict = #或者這樣設定文字旋轉

#ax.set_xticklabels([''] + list(df.columns), rotation=90) #或者直接設定到這裡

# axes.set_xticklabels(labels, fontdict=none, minor=false, **kwargs)

ax.set_xticklabels([''] + list(df.columns), fontdict=fontdict)

ax.set_yticklabels([''] + list(df.index))

plt.show()

如果不設定fontdict,橫軸的文字是橫著的,疊加在一起,所以要設定旋轉90度。

fontdict的更多文字屬性設定可以在 裡面的property找到

最後顯示的結果是:

顏色越深的表示這兩個詞的相似度最高,比如50和50,24對應塊的顏色挺深的。

。可以在matplotlib documentation找到

文字資料視覺化 練習

coding utf 8 matplotlib是乙個 python 的 2d數學繪相簿 安裝 pip install matplotlib import matplotlib.pyplot as plt jieba中文分詞庫 安裝 pip install jieba import jieba wor...

文字視覺化分析 構建文字視覺化和分析應用程式

文字視覺化分析 存檔日期 2019年5月15日 首次發布 2013年3月19日 文字視覺化是檢視和分析指定文字在說什麼的有效方法。學習將eclipse與開放源 文字視覺化和分析工具相結合,以構建乙個視覺化並比較兩個文字的詞波應用程式。2013年4月2日 更新了ibm infosphere strea...

相關矩陣視覺化包ggcorrplot

基於ggplot2包以及corrplot包的相關矩陣視覺化包ggcorrplot,ggcorrplot包提供對相關矩陣重排序以及在相關圖中展示顯著性水平的方法,同時也能計算相關性p value library ggcorrplot 計算相關矩陣 cor 計算結果不提供p value 用ggcorrp...