溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2023-05-17 13:50:51 來(lái)源:億速云 閱讀:122 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“python共現(xiàn)矩陣怎么實(shí)現(xiàn)”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“python共現(xiàn)矩陣怎么實(shí)現(xiàn)”吧!

什么是共現(xiàn)矩陣

比如我們有兩句話:

ls = ['我永遠(yuǎn)喜歡三上悠亞', '三上悠亞又出新作了']

在jieba分詞下我們可以得到如下效果:

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

我們就可以構(gòu)建一個(gè)以關(guān)鍵詞的共現(xiàn)矩陣:

['',    '我', '永遠(yuǎn)', '喜歡', '三上', '悠亞', '又', '出', '新作', '了']
['我',    0,      1,     1,     1,    1,    0,    0,      0,     0]
['永遠(yuǎn)',  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]]

解釋一下,“我永遠(yuǎn)喜歡三上悠亞”,這一句話中,“我”和“永遠(yuǎn)”共同出現(xiàn)了一次,在共現(xiàn)矩陣對(duì)應(yīng)的[ i ] [ j ]和[ j ][ i ]上+1,并依次類推。

基于這個(gè)原因,我們可以發(fā)現(xiàn),共現(xiàn)矩陣的特點(diǎn)是:

  • 共現(xiàn)矩陣的[0][0]為空。

  • 共現(xiàn)矩陣的第一行第一列是關(guān)鍵詞。

  • 對(duì)角線全為0。

  • 共現(xiàn)矩陣其實(shí)是一個(gè)對(duì)稱矩陣。

當(dāng)然,在實(shí)際的操作中,這些關(guān)鍵詞是需要經(jīng)過(guò)清洗的,這樣的可視化才干凈。

共現(xiàn)矩陣的構(gòu)建思路
  • 每篇文章關(guān)鍵詞的二維數(shù)組data_array。

  • 所有關(guān)鍵詞的集合set_word。

  • 建立關(guān)鍵詞長(zhǎng)度+1的矩陣matrix。

  • 賦值矩陣的第一行與第一列為關(guān)鍵詞。

  • 設(shè)置矩陣對(duì)角線為0。

  • 遍歷formated_data,讓取出的行關(guān)鍵詞和取出的列關(guān)鍵詞進(jìn)行組合,共現(xiàn)則+1。

共現(xiàn)矩陣的代碼實(shí)現(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)錯(cuò)誤:', reason)
        return data_array, set_word
# 初始化矩陣
def build_matirx(set_word):
    edge = len(set_word) + 1  # 建立矩陣,矩陣的高度和寬度為關(guān)鍵詞集合的長(zhǎng)度+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
# 計(jì)算各個(gè)關(guān)鍵詞的共現(xiàn)次數(shù)
def count_matrix(matrix, formated_data):
    for row in range(1, len(matrix)):
        # 遍歷矩陣第一行,跳過(guò)下標(biāo)為0的元素
        for col in range(1, len(matrix)):
            # 遍歷矩陣第一列,跳過(guò)下標(biāo)為0的元素
            # 實(shí)際上就是為了跳過(guò)matrix中下標(biāo)為[0][0]的元素,因?yàn)閇0][0]為空,不為關(guān)鍵詞
            if matrix[0][row] == matrix[col][0]:
                # 如果取出的行關(guān)鍵詞和取出的列關(guān)鍵詞相同,則其對(duì)應(yīng)的共現(xiàn)次數(shù)為0,即矩陣對(duì)角線為0
                matrix[col][row] = str(0)
            else:
                counter = 0  # 初始化計(jì)數(shù)器
                for ech in formated_data:
                    # 遍歷格式化后的原始數(shù)據(jù),讓取出的行關(guān)鍵詞和取出的列關(guān)鍵詞進(jì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)矩陣(共詞矩陣)計(jì)算

共現(xiàn)矩陣(共詞矩陣)

統(tǒng)計(jì)文本中兩兩詞組之間共同出現(xiàn)的次數(shù),以此來(lái)描述詞組間的親密度

code(我這里求的對(duì)角線元素為該字段在文本中出現(xiàn)的總次數(shù)):

import pandas as pd
def gx_matrix(vol_li):
    # 整合一下,輸入是df列,輸出直接是矩陣
    names = locals()
    all_col0 = []   # 用來(lái)后續(xù)求所有字段的集合
    for row in vol_li:
        all_col0 += row
	    for each in row:  # 對(duì)每行的元素進(jìn)行處理,存在該字段字典的話,再進(jìn)行后續(xù)判斷,否則創(chuàng)造該字段字典
	        try:
	            for each3 in row:  # 對(duì)已存在字典,循環(huán)該行每個(gè)元素,存在則在已有次數(shù)上加一,第一次出現(xiàn)創(chuàng)建鍵值對(duì)“字段:1”
	                try:
	                    names['dic_' + each][each3] = names['dic_' + each][each3] + 1  # 嘗試,一起出現(xiàn)過(guò)的話,直接加1
	                except:
	                    names['dic_' + each][each3] = 1  # 沒(méi)有的話,第一次加1
	        except:
	            names['dic_' + each] = dict.fromkeys(row, 1)  # 字段首次出現(xiàn),創(chuàng)造字典
    # 根據(jù)生成的計(jì)數(shù)字典生成矩陣
    all_col = list(set(all_col0))   # 所有的字段(所有動(dòng)物的集合)
    all_col.sort(reverse=False)  # 給定詞匯列表排序排序,為了和生成空矩陣的橫向列名一致
    df_final0 = pd.DataFrame(columns=all_col)  # 生成空矩陣
    for each in all_col:  # 空矩陣中每列,存在給字段字典,轉(zhuǎn)為一列存入矩陣,否則先創(chuàng)造全為零的字典,再填充進(jìn)矩陣
        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)

輸入是整成這個(gè)樣子的series

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

求出每個(gè)字段與各字段的出現(xiàn)次數(shù)的字典

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

最后轉(zhuǎn)為df

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

補(bǔ)充一點(diǎn)

這里如果用大象所在列,除以大象出現(xiàn)的次數(shù),比值高的,表明兩者一起出現(xiàn)的次數(shù)多,如果這列比值中,有兩個(gè)元素a和b的比值均大于0.8(也不一定是0.8啦),就是均比較高,則說(shuō)明a和b和大象三個(gè)一起出現(xiàn)的次數(shù)多?。?!

即可以求出文本中經(jīng)常一起出現(xiàn)的詞組搭配,比如這里的第二列,大象一共出現(xiàn)3次,與老虎出現(xiàn)3次,與豬出現(xiàn)2次,則可以推導(dǎo)出大象,老虎,豬一起出現(xiàn)的概率較高。

也可以把出現(xiàn)總次數(shù)拎出來(lái),放在最后一列,則代碼為:

# 計(jì)算每個(gè)字段的出現(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é)果為

python共現(xiàn)矩陣怎么實(shí)現(xiàn)

到此,相信大家對(duì)“python共現(xiàn)矩陣怎么實(shí)現(xiàn)”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI