字典特征提取和文本特征抽取

什么叫字典特征提取?

字典内容转化成计算机可以处理的数值

比如现在有个字典:

    data = [
	    {"city":"北京", "tempeture":100, "age":11} , 
	    {"city":"上海", "tempeture":60,"age":12} ,
	    {"city":"深圳", "tempeture":20,"age":13}
	     ]
    

分别是老三,老四,老五的个人基本信息
我们想提取出来这几个人的特征值,也就是给我用一个向量,表示某个独一无二的人的特征

我们先给出代码

#coding=utf-8
#特征提取
#首先导入转换器类
from sklearn.feature_extraction  import  DictVectorizer

def dec_demo():
    data = [{"city":"北京", "tempeture":100, "age":11} , {"city":"上海", "tempeture":60,"age":12} ,{"city":"深圳", "tempeture":20,"age":13} ]
    
    # 1. 实例化一个转换模块,不使用稀疏矩阵
    dt2= DictVectorizer( sparse=False )
    
    # 2. 调用fit_transform()
    result = dt.fit_transform(data)
    print(result)
    
    return None
    
    
if __name__=="__main__":
    dec_demo()

结果是:

[[ 11.   0.   1.   0. 100.]
 [ 12.   1.   0.   0.  60.]
 [ 13.   0.   0.   1.  20.]]

特征模板是: [‘age’, ‘city=上海’, ‘city=北京’, ‘city=深圳’, ‘tempeture’]

这就叫做字典特征提取


那么以此类推,文本特征提取也是类似,依靠向量表示数

#coding=utf-8
from sklearn.feature_extraction.text import CountVectorizer

def context_Demo():
    
    '''文本特征抽取'''
    context=["life is hard,we need to envisage ourselves, life is"]
    
    # 实例化一个内容转换器
    CV =  CountVectorizer()
    
    # 调用fit_transform
    result = CV.fit_transform(context)
    
    print(result.toarray())
    print("\n")
    print(CV.get_feature_names()) 
    
if  __name__ == "__main__":
    context_Demo()

结果是:

[[1 1 2 2 1 1 1 1]]

['envisage', 'hard', 'is', 'life', 'need', 'ourselves', 'to', 'we']

请注意

不能设置sparse=false
反而使用 bunch (就是特征抽取之后返回的结果) 的 toarray()方法

发布了35 篇原创文章 · 获赞 5 · 访问量 2425

猜你喜欢

转载自blog.csdn.net/qq_24884193/article/details/104076321