0
点赞
收藏
分享

微信扫一扫

文本特征提取专题_以python为工具【Python机器学习系列(十二)】

文章目录


      ʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞ
                 在这里插入图片描述请添加图片描述请添加图片描述请添加图片描述在这里插入图片描述
    ʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞʚʕ̯•͡˔•̯᷅ʔɞ


大家好,我是侯小啾!在这里插入图片描述

在这里插入图片描述今天分享的话题是,文本特征的提取。具体内容请见下文:


1.字典文本特征提取 DictVectorizer()

1.1 one-hot编码

创建一个字典,观察如下数据形式的变化:

import pandas as pd
from sklearn.feature_extraction import DictVectorizer


data = [{'city': '洛阳', 'temperature': 39},
        {'city': '成都', 'temperature': 41},
        {'city': '宁波', 'temperature': 42},
        {'city': '佛山', 'temperature': 38}]

df1 = pd.DataFrame(data)
print(df1)

# one-hot编码 因为temperature是数值型的,所以会保留原始值,只有字符串类型的才会生成虚拟变量
df2 = pd.get_dummies(df1)
print(df2)

输出如下:
      在这里插入图片描述


1.2 字典数据转sparse矩阵

使用DictVectorizer()创建字典特征提取模型

# 1.创建对象  默认sparse=True 返回的是sparse矩阵;  sparse=False  返回的是ndarray矩阵
transfer = DictVectorizer()
# 2.转化数据并训练
trans_data = transfer.fit_transform(data)
print(transfer.get_feature_names_out()) 
print(trans_data)

       在这里插入图片描述

使用sparse矩阵没有显示0数据,节约了内存,更为简洁,这一点比ndarray矩阵更好。


2.英文文本特征提取

文本特征提取使用的是CountVectorizer文本特征提取模型,这里准备了一段英文文本(I have a dream)。统计词频并得到sparse矩阵,代码如下所示:

CountVectorizer()没有sparse参数,默认采用sparse矩阵格式。且可以通过stop_words指定停用词。

from sklearn.feature_extraction.text import CountVectorizer


data = ["I have a dream that one day this nation will rise up and live out the true meaning of its creed",
        "We hold these truths to be self-evident, that all men are created equal",
        "I have a dream that one day on the red hills of Georgia, "
        "the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood",
        "I have a dream that one day even the state of Mississippi",
        " a state sweltering with the heat of injustice",
        "sweltering with the heat of oppression",
        "will be transformed into an oasis of freedom and justice",
        "I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character",
        "I have a dream today"]


# CountVectorizer文本特征提取模型

# 1.实例化  将"is"标记为停用词
c_transfer = CountVectorizer(stop_words=["is"])

# 2.调用fit_transform
c_trans_data = c_transfer.fit_transform(data)


# 打印特征名称
print(c_transfer.get_feature_names_out())

# 打印sparse矩阵
print(c_trans_data)

输出结果如下图所示:
    在这里插入图片描述


3.中文文本特征提取

准备一段中文文本(data.txt),以水浒传中风雪山神庙情节为例:

对中文提取文本特征,需要安装并使用到jieba库。使用该库将文本处理成为空格连接词语的格式,再使用CountVectorizer文本特征提取模型进行提取即可。

代码示例如下:

import jieba
from sklearn.feature_extraction.text import CountVectorizer


# 将文本转为以空格相连的字符串
def cut_word(sent):
    return " ".join(list(jieba.cut(sent)))


# 将文本以行为单位,去除空格,并置于列表中。格式形如:["第一行","第二行",..."n"]
with open("./论文.txt", "r") as f:
    data = [line.replace("\n", "") for line in f.readlines()]

lis = []
# 将每一行的词汇以空格连接 
for temp in data:
    lis.append(cut_word(temp))

transfer = CountVectorizer()
trans_data = transfer.fit_transform(lis)
print(transfer.get_feature_names())
# 输出sparse数组
print(trans_data)
# 转为ndarray数组(如果需要)
print(trans_data.toarray())

程序执行效果如下:
在这里插入图片描述


转换得到的ndarray数组形式(如果需要)如图所示:
  在这里插入图片描述


4. TF-IDF 文本特征提取 TfidfVectorizer()

TF-IDF文本提取器可以用来评估一字词对于一个文件集或者一个语料库中的其中一份文件的重要程度。
代码展示如下:

from sklearn.feature_extraction.text import TfidfVectorizer
import jieba


def cut_word(sent):
    return " ".join(list(jieba.cut(sent)))


with open("data.txt", "r") as f:
    data = [line.replace("\n", "") for line in f.readlines()]

lis = []
for temp in data:
    # print(cut_word(temp))
    lis.append(cut_word(temp))


transfer = TfidfVectorizer()
print(transfer.get_feature_names())
print(trans_data)

程序执行结果如下:
在这里插入图片描述


本次分享就到这里,小啾感谢您的关注与支持!
🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ🌹꧔ꦿ

举报

相关推荐

0 条评论