当前位置:   article > 正文

【Python】代码实现TF-IDF算法将文档向量化(os.listdir())_python tf-idf将数据向量化

python tf-idf将数据向量化

所用数据为经典的20Newsgroup数据

数据集链接:http://qwone.com/~jason/20Newsgroups/(比较慢,建议采用Science上网等其他方法下载)

直接上完整代码:

# -*- coding: utf-8 -*-
import os 
import math
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

def TF(wordSet,split):
    tf = dict.fromkeys(wordSet, 0)
    for word in split:
        tf[word] += 1
    return tf

def IDF(tfList): 
    idfDict = dict.fromkeys(tfList[0],0) #词为key,初始值为0
    N = len(tfList)  #总文档数量 
    for tf in tfList: # 遍历字典中每一篇文章
        for word, count in tf.items(): #遍历当前文章的每一个词
            if count > 0 : #当前遍历的词语在当前遍历到的文章中出现
                idfDict[word] += 1 #包含词项tj的文档的篇数df+1  
    for word, Ni in idfDict.items(): #利用公式将df替换为逆文档频率idf
        idfDict[word] = math.log10(N/Ni)  #N,Ni均不会为0
    return idfDict   #返回逆文档频率IDF字典

def TFIDF(tf, idfs): #tf词频,idf逆文档频率
    tfidf = {}
    for word, tfval in tf.items():
        tfidf[word] = tfval * idfs[word]
    return tfidf
    
if __name__ == "__main__":
    #1 获取文件
    text=[] 
    name_all = os.listdir(r'20news-bydate-train/alt.atheism/')
    for i in range(len(name_all)):
        name = "20news-bydate-train/alt.atheism/" + name_all[i]
        f = open(name,"rb")
        str1=f.read()
        text.append(str1)
        f.close()
    #2 将每篇文档进行分词
    wordSet = {}
    split_list = []
    for i in range(len(text)):
        split =str(text[i]).split(' ')
        split_list.append(split)
        wordSet = set(wordSet ).union(split)#通过set去重来构建词库
    #3 统计每篇文章各项词语的词频
    tf = []
    for i in range(len(split_list)):
        tf.append(TF(wordSet,split_list[i]))
    #4 计算文档集的逆文档频率
    idfs = IDF(tf)
    #5 tf*idf = tfidf算法
    tfidf = []
    for i in range(len(tf)):
        tfidf.append(TFIDF(tf[i], idfs))
    
    print(pd.DataFrame(tfidf))  #可转换为DataFrame类型用于后序操作

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

本例读取了480篇英文文档,并将其向量化
在这里插入图片描述
最终获取到了一个480*31412维的DataFrame类型数据,可根据后续PCA降维和相关分类算法的实际需要将其转换为ndarray类型、矩阵类型(scipy.sparse.csr.csr_matrix)等。

Python os.listdir() 方法

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/347657
推荐阅读
相关标签
  

闽ICP备14008679号