博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
理解sklearn.feature.text中的CountVectorizer和TfidfVectorizer
阅读量:6909 次
发布时间:2019-06-27

本文共 1373 字,大约阅读时间需要 4 分钟。

"""理解sklearn中的CountVectorizer和TfidfVectorizer"""from collections import Counterimport numpy as npfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizersentences = ["there is a dog dog", "here is a cat"]count_vec = CountVectorizer()a = count_vec.fit_transform(sentences)print(a.toarray())print(count_vec.vocabulary_)"""输出{'dog': 1, 'there': 4, 'here': 2, 'cat': 0, 'is': 3}表示每个词汇对应的坐标"""print("=" * 10)tf_vec = TfidfVectorizer()b = tf_vec.fit_transform(sentences)print(b.toarray())print(tf_vec.vocabulary_)print(tf_vec.idf_)  # 逆文档频率print(tf_vec.get_feature_names())def mytf_idf(s):    # 自己实现tfidf    words = tf_vec.get_feature_names()    tf_matrix = np.zeros((len(s), len(words)), dtype=np.float32)    smooth = 1    # 初始值加上平滑因子    df_matrix = np.ones(len(words), dtype=np.float32) * smooth    for i in range(len(s)):        s_words = s[i].split()        for j in range(len(words)):            cnt = Counter(s_words).get(words[j], 0)            tf_matrix[i][j] = cnt            if cnt > 0:                df_matrix[j] += 1    # idf一定是大于1的数值    idf_matrix = np.log((len(s) + smooth) / df_matrix) + 1    matrix = tf_matrix * idf_matrix    matrix = matrix / np.linalg.norm(matrix, 2, axis=1).reshape(matrix.shape[0], 1)    print(matrix)print("=" * 10)mytf_idf(sentences)"""TODO:* IDF可以学到,通过神经网络反向传播来学习IDF而不是直接计算得出* CountVectorizer有时不需要考虑个数,只需要知道是否出现过即可"""

转载地址:http://gffcl.baihongyu.com/

你可能感兴趣的文章
jQuery hover 延时器实现代码
查看>>
ArcGIS JS 学习笔记3 实现百度风格的BubblePopup
查看>>
JavaScript之字符串引号的使用技巧
查看>>
linux如何关闭selinux?
查看>>
初识CSS
查看>>
Android开发常用代码片段
查看>>
微信小程序使用场景及取名“潜”规则
查看>>
Atitit nodejs5 nodejs6 nodejs 7.2.1 新特性attialx总结
查看>>
回顾 git 常用命令
查看>>
第四章 Spring.Net 如何管理您的类___统一资源访问接口
查看>>
最大流+最小费用最大流
查看>>
java-mybaits-00103-入门程序原生的【查、增、删、改】
查看>>
LayoutInflater
查看>>
用sourceTree提交代码时遇到的问题
查看>>
Mysql第一周
查看>>
深入理解 Android 消息机制原理
查看>>
1.一个WEB应用的开发流程
查看>>
centos7 安装mysql5.6.32
查看>>
前端JavaScript实现跨域的方式(转)
查看>>
原来你是这样的http2......
查看>>