python?共現(xiàn)矩陣的實現(xiàn)代碼
python共現(xiàn)矩陣實現(xiàn)
最近在學(xué)習(xí)python詞庫的可視化,其中有一個依據(jù)共現(xiàn)矩陣制作的可視化,感覺十分炫酷,便以此復(fù)刻。
項目背景
本人利用爬蟲獲取各大博客網(wǎng)站的文章,在進行jieba分詞,得到每篇文章的關(guān)鍵詞,對這些關(guān)鍵詞進行共現(xiàn)矩陣的可視化。
什么是共現(xiàn)矩陣
比如我們有兩句話:
ls = ['我永遠喜歡三上悠亞', '三上悠亞又出新作了']
在jieba分詞下我們可以得到如下效果:
我們就可以構(gòu)建一個以關(guān)鍵詞的共現(xiàn)矩陣:
['', '我', '永遠', '喜歡', '三上', '悠亞', '又', '出', '新作', '了'] ['我', 0,1, 1, 1, 1, 0, 0,0, 0] ['永遠', 1,0, 1,1, 1, 0, 0, 0, 0] ['喜歡'1,1, 0,1, 1, 0, 0, 0, 0] ['三上', 1,1, 1,0, 1, 1, 1, 1, 1] ['悠亞', 1,1, 1,1, 0, 1, 1, 1, 1] ['又', 0,0, 0,1, 1, 0, 1, 1, 1] ['出', 0,0, 0,1, 1, 1, 0, 1, 1] ['新作', 0,0, 0,1, 1, 1, 1, 0, 1] ['了', 0,0, 0,1, 1, 1, 1, 1, 0]]
解釋一下,“我永遠喜歡三上悠亞”,這一句話中,“我”和“永遠”共同出現(xiàn)了一次,在共現(xiàn)矩陣對應(yīng)的[ i ] [ j ]和[ j ][ i ]上+1,并依次類推。
基于這個原因,我們可以發(fā)現(xiàn),共現(xiàn)矩陣的特點是:
- 共現(xiàn)矩陣的[0][0]為空。
- 共現(xiàn)矩陣的第一行第一列是關(guān)鍵詞。
- 對角線全為0。
- 共現(xiàn)矩陣其實是一個對稱矩陣。
當(dāng)然,在實際的操作中,這些關(guān)鍵詞是需要經(jīng)過清洗的,這樣的可視化才干凈。
共現(xiàn)矩陣的構(gòu)建思路
- 每篇文章關(guān)鍵詞的二維數(shù)組data_array。
- 所有關(guān)鍵詞的集合set_word。
- 建立關(guān)鍵詞長度+1的矩陣matrix。
- 賦值矩陣的第一行與第一列為關(guān)鍵詞。
- 設(shè)置矩陣對角線為0。
- 遍歷formated_data,讓取出的行關(guān)鍵詞和取出的列關(guān)鍵詞進行組合,共現(xiàn)則+1。
共現(xiàn)矩陣的代碼實現(xiàn)
# coding:utf-8 import numpy as np import pandas as pd import jieba.analyse import os # 獲取關(guān)鍵詞 def Get_file_keywords(dir): data_array = [] # 每篇文章關(guān)鍵詞的二維數(shù)組 set_word = [] # 所有關(guān)鍵詞的集合 try: fo = open('dic_test.txt', 'w+', encoding='UTF-8') # keywords = fo.read() for home, dirs, files in os.walk(dir): # 遍歷文件夾下的每篇文章 for filename in files: fullname = os.path.join(home, filename) f = open(fullname, 'r', encoding='UTF-8') sentence = f.read() words = " ".join(jieba.analyse.extract_tags(sentence=sentence, topK=30, withWeight=False, allowPOS=('n'))) # TF-IDF分詞 words = words.split(' ') data_array.append(words) for word in words: if word not in set_word:set_word.append(word) set_word = list(set(set_word)) # 所有關(guān)鍵詞的集合 return data_array, set_word except Exception as reason: print('出現(xiàn)錯誤:', reason) return data_array, set_word # 初始化矩陣 def build_matirx(set_word): edge = len(set_word) + 1 # 建立矩陣,矩陣的高度和寬度為關(guān)鍵詞集合的長度+1 '''matrix = np.zeros((edge, edge), dtype=str)''' # 另一種初始化方法 matrix = [['' for j in range(edge)] for i in range(edge)] # 初始化矩陣 matrix[0][1:] = np.array(set_word) matrix = list(map(list, zip(*matrix))) matrix[0][1:] = np.array(set_word) # 賦值矩陣的第一行與第一列 return matrix # 計算各個關(guān)鍵詞的共現(xiàn)次數(shù) def count_matrix(matrix, formated_data): for row in range(1, len(matrix)): # 遍歷矩陣第一行,跳過下標為0的元素 for col in range(1, len(matrix)): # 遍歷矩陣第一列,跳過下標為0的元素 # 實際上就是為了跳過matrix中下標為[0][0]的元素,因為[0][0]為空,不為關(guān)鍵詞 if matrix[0][row] == matrix[col][0]: # 如果取出的行關(guān)鍵詞和取出的列關(guān)鍵詞相同,則其對應(yīng)的共現(xiàn)次數(shù)為0,即矩陣對角線為0 matrix[col][row] = str(0) else: counter = 0 # 初始化計數(shù)器 for ech in formated_data: # 遍歷格式化后的原始數(shù)據(jù),讓取出的行關(guān)鍵詞和取出的列關(guān)鍵詞進行組合, # 再放到每條原始數(shù)據(jù)中查詢 if matrix[0][row] in ech and matrix[col][0] in ech:counter += 1 else:continue matrix[col][row] = str(counter) return matrix def main(): formated_data, set_word = Get_file_keywords(r'D:\untitled\test') print(set_word) print(formated_data) matrix = build_matirx(set_word) matrix = count_matrix(matrix, formated_data) data1 = pd.DataFrame(matrix) data1.to_csv('data.csv', index=0, columns=None, encoding='utf_8_sig') main()
共現(xiàn)矩陣(共詞矩陣)計算
共現(xiàn)矩陣(共詞矩陣)
統(tǒng)計文本中兩兩詞組之間共同出現(xiàn)的次數(shù),以此來描述詞組間的親密度
code(我這里求的對角線元素為該字段在文本中出現(xiàn)的總次數(shù)):
import pandas as pd def gx_matrix(vol_li): # 整合一下,輸入是df列,輸出直接是矩陣 names = locals() all_col0 = []# 用來后續(xù)求所有字段的集合 for row in vol_li: all_col0 += row for each in row: # 對每行的元素進行處理,存在該字段字典的話,再進行后續(xù)判斷,否則創(chuàng)造該字段字典 try: for each1 in row: # 對已存在字典,循環(huán)該行每個元素,存在則在已有次數(shù)上加一,第一次出現(xiàn)創(chuàng)建鍵值對“字段:1” try: names['dic_' + each][each1] = names['dic_' + each][each1] + 1 # 嘗試,一起出現(xiàn)過的話,直接加1 except: names['dic_' + each][each1] = 1 # 沒有的話,第一次加1 except: names['dic_' + each] = dict.fromkeys(row, 1) # 字段首次出現(xiàn),創(chuàng)造字典 # 根據(jù)生成的計數(shù)字典生成矩陣 all_col = list(set(all_col0))# 所有的字段(所有動物的集合) all_col.sort(reverse=False) # 給定詞匯列表排序排序,為了和生成空矩陣的橫向列名一致 df_final0 = pd.DataFrame(columns=all_col) # 生成空矩陣 for each in all_col: # 空矩陣中每列,存在給字段字典,轉(zhuǎn)為一列存入矩陣,否則先創(chuàng)造全為零的字典,再填充進矩陣 try: temp = pd.DataFrame(names['dic_' + each], index=[each]) except: names['dic_' + each] = dict.fromkeys(all_col, 0) temp = pd.DataFrame(names['dic_' + each], index=[each]) df_final0 = pd.concat([df_final0, temp]) # 拼接 df_final = df_final0.fillna(0) return df_final if __name__ == '__main__': temp1 = ['狗', '獅子', '孔雀', '豬'] temp2 = ['大象', '獅子', '老虎', '豬'] temp3 = ['大象', '北極熊', '老虎', '豬'] temp4 = ['大象', '狗', '老虎', '小雞'] temp5 = ['狐貍', '獅子', '老虎', '豬'] temp_all = [temp2, temp1, temp3, temp4, temp5] vol_li = pd.Series(temp_all) df_matrix = gx_matrix(vol_li) print(df_matrix)
輸入是整成這個樣子的series
求出每個字段與各字段的出現(xiàn)次數(shù)的字典
最后轉(zhuǎn)為df
補充一點
這里如果用大象所在列,除以大象出現(xiàn)的次數(shù),比值高的,表明兩者一起出現(xiàn)的次數(shù)多,如果這列比值中,有兩個元素a和b的比值均大于0.8(也不一定是0.8啦),就是均比較高,則說明a和b和大象三個一起出現(xiàn)的次數(shù)多?。?!
即可以求出文本中經(jīng)常一起出現(xiàn)的詞組搭配,比如這里的第二列,大象一共出現(xiàn)3次,與老虎出現(xiàn)3次,與豬出現(xiàn)2次,則可以推導(dǎo)出大象,老虎,豬一起出現(xiàn)的概率較高。
也可以把出現(xiàn)總次數(shù)拎出來,放在最后一列,則代碼為:
# 計算每個字段的出現(xiàn)次數(shù),并列為最后一行 df_final['all_times'] = '' for each in df_final0.columns: df_final['all_times'].loc[each] = df_final0.loc[each, each]
放在上述代碼df_final = df_final0.fillna(0)的后面即可
結(jié)果為
我第一次放代碼上來的時候中間有一塊縮進錯了,感謝提出問題的同學(xué)的提醒,現(xiàn)在是更正過的代碼!??!
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。