函数说明:

1 CountVectorizer(ngram_range=(2, 2)) 进行字符串的前后组合,构造出新的词袋标签

参数说明:ngram_range=(2, 2) 表示选用2个词进行前后的组合,构成新的标签值

Ngram模型表示的是,对于词频而言,只考虑一个词,这里我们在CountVectorizer统计词频时,传入ngram_range=(2, 2)来构造新的词向量的组合

好比一句话'I like you'

如果ngram_range = (2, 2)表示只选取前后的两个词构造词组合 :词向量组合为:’I like‘ 和 ’like you‘

如果ngram_range = (1, 3) 表示选取1到3个词做为组合方式: 词向量组合为: 'I', 'like', 'you', 'I like', 'like you', 'I like you' 构成词频标签

代码:

第一步:构造Dataframe格式,并数组化数据

第二步:构造函数进行分词和去除停用词,并使用空格进行串接,为了分词做准备

第三步:np.vectorize 向量化函数,并调用函数进行分词和去除停用词

第四步:使用CountVectorizer(ngram_range(2, 2)) 进行文本的词向量拼接

import pandas as pd
import numpy as np
import re
import nltk #pip install nltk corpus = ['The sky is blue and beautiful.',
'Love this blue and beautiful sky!',
'The quick brown fox jumps over the lazy dog.',
'The brown fox is quick and the blue dog is lazy!',
'The sky is very blue and the sky is very beautiful today',
'The dog is lazy but the brown fox is quick!'
] labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals'] # 第一步:构建DataFrame格式数据
corpus = np.array(corpus)
corpus_df = pd.DataFrame({'Document': corpus, 'categoray': labels}) # 第二步:构建函数进行分词和停用词的去除
# 载入英文的停用词表
stopwords = nltk.corpus.stopwords.words('english')
# 建立词分割模型
cut_model = nltk.WordPunctTokenizer()
# 定义分词和停用词去除的函数
def Normalize_corpus(doc):
# 去除字符串中结尾的标点符号
doc = re.sub(r'[^a-zA-Z0-9\s]', '', string=doc)
# 是字符串变小写格式
doc = doc.lower()
# 去除字符串两边的空格
doc = doc.strip()
# 进行分词操作
tokens = cut_model.tokenize(doc)
# 使用停止用词表去除停用词
doc = [token for token in tokens if token not in stopwords]
# 将去除停用词后的字符串使用' '连接,为了接下来的词袋模型做准备
doc = ' '.join(doc) return doc # 第三步:向量化函数和调用函数
# 向量化函数,当输入一个列表时,列表里的数将被一个一个输入,最后返回也是一个个列表的输出
Normalize_corpus = np.vectorize(Normalize_corpus)
# 调用函数进行分词和去除停用词
corpus_norm = Normalize_corpus(corpus)
print(corpus_norm)

# 第四步:使用ngram_range构造组合的词袋标签
from sklearn.feature_extraction.text import CountVectorizer
CV = CountVectorizer(ngram_range=(2, 2))
CV.fit(corpus_norm)
vocs = CV.get_feature_names()
print(vocs)
corpus_array = CV.transform(corpus_norm).toarray()
corpus_norm_df = pd.DataFrame(corpus_array, columns=vocs)
print(corpus_norm_df.head())

部分的组合结果

机器学习入门-文本数据-构造Ngram词袋模型 1.CountVectorizer(ngram_range) 构建Ngram词袋模型的更多相关文章

  1. 机器学习入门-文本数据-构造词频词袋模型 1.re.sub(进行字符串的替换) 2.nltk.corpus.stopwords.words(获得停用词表) 3.nltk.WordPunctTokenizer(对字符串进行分词操作) 4.np.vectorize(对函数进行向量化) 5. CountVectorizer(构建词频的词袋模型)

    函数说明: 1. re.sub(r'[^a-zA-Z0-9\s]', repl='', sting=string)  用于进行字符串的替换,这里我们用来去除标点符号 参数说明:r'[^a-zA-Z0- ...

  2. 机器学习入门-文本数据-构造Tf-idf词袋模型(词频和逆文档频率) 1.TfidfVectorizer(构造tf-idf词袋模型)

    TF-idf模型:TF表示的是词频:即这个词在一篇文档中出现的频率 idf表示的是逆文档频率, 即log(文档的个数/1+出现该词的文档个数)  可以看出出现该词的文档个数越小,表示这个词越稀有,在这 ...

  3. 机器学习入门-文本特征-使用LDA主题模型构造标签 1.LatentDirichletAllocation(LDA用于构建主题模型) 2.LDA.components(输出各个词向量的权重值)

    函数说明 1.LDA(n_topics, max_iters, random_state)  用于构建LDA主题模型,将文本分成不同的主题 参数说明:n_topics 表示分为多少个主题, max_i ...

  4. 机器学习入门-贝叶斯构造LDA主题模型,构造word2vec 1.gensim.corpora.Dictionary(构造映射字典) 2.dictionary.doc2vec(做映射) 3.gensim.model.ldamodel.LdaModel(构建主题模型)4lda.print_topics(打印主题).

    1.dictionary = gensim.corpora.Dictionary(clean_content)  对输入的列表做一个数字映射字典, 2. corpus = [dictionary,do ...

  5. 机器学习入门-文本特征-word2vec词向量模型 1.word2vec(进行word2vec映射编码)2.model.wv['sky']输出这个词的向量映射 3.model.wv.index2vec(输出经过映射的词名称)

    函数说明: 1. from gensim.model import word2vec  构建模型 word2vec(corpus_token, size=feature_size, min_count ...

  6. 【机器学习】机器学习入门02 - 数据拆分与测试&算法评价与调整

    0. 前情回顾 上一周的文章中,我们通过kNN算法了解了机器学习的一些基本概念.我们自己实现了简单的kNN算法,体会了其过程.这一周,让我们继续机器学习的探索. 1. 数据集的拆分 上次的kNN算法介 ...

  7. Jmeter入门16 数据构造之随机数Random Variable & __Random函数

     接口测试有时参数使用随机数构造.jmeter添加随机数两种方式 1  添加配置 > Random Variable  2  __Random函数   ${__Random(1000,9999) ...

  8. Tensorflow机器学习入门——读取数据

    TensorFlow 中可以通过三种方式读取数据: 一.通过feed_dict传递数据: input1 = tf.placeholder(tf.float32) input2 = tf.placeho ...

  9. 如何使用 scikit-learn 为机器学习准备文本数据

    欢迎大家前往云+社区,获取更多腾讯海量技术实践干货哦~ 文本数据需要特殊处理,然后才能开始将其用于预测建模. 我们需要解析文本,以删除被称为标记化的单词.然后,这些词还需要被编码为整型或浮点型,以用作 ...

随机推荐

  1. 自定义鼠标右键(层叠式菜单:cascading menu)

    Author:KillerLegend From:http://www.cnblogs.com/killerlegend/p/3575391.html Date:Tuesday, February 1 ...

  2. mariadb semi plugin遇到的坑

    安装完semi plugin运行一段时间后,重启mariadb, 突然发现canal无法解析数据了,一直在报错,然后登陆mariadb, show plugins竟然没有看到之前安装的semi plu ...

  3. VRRP、Track与NQA联动配置举例(Master监视上行链路)

    原文 http://www.h3c.com/cn/d_201708/1018729_30005_0.htm#_Toc488338729 1. 组网需求 Host A需要访问Internet上的Host ...

  4. AndroidStudio2.2.2 打开ddms快捷键

    按两下shift键,后在弹出的对话框中输入Android Device,在出现的选项中单击即可,如图.

  5. ubuntu下 net core 安装web模板

    ---恢复内容开始--- 今天想试试在Linux用C#开发WebAPI,查了下,要用: dotnet new -t Web 来建立工程,结果我试了下,出来这段: Invalid input switc ...

  6. selenuim和phantonJs处理网页动态加载数据的爬取

    一.图片懒加载 什么是图片懒加载? 案例分析:抓取站长素材http://sc.chinaz.com/中的图片数据 #!/usr/bin/env python # -*- coding:utf-8 -* ...

  7. oi造数据

    #include<cstdio> #include<cstdlib> #include<cstring> #include<ctime> #includ ...

  8. org.springframework.boot.builder.SpringApplicationBuilder.<init>

    新建了一个Spring cloud项目,启动时报错org.springframework.boot.builder.SpringApplicationBuilder.<init> 翻阅资料 ...

  9. error while obtaining ui hierarchy xml file...用 uiautomatorviewer 获取安卓手机软件页面时报错

    Error while obtaining UI hierarchy XML file: com.android.ddmlib.SyncException: Remote object doesn't ...

  10. StanFord ML 笔记 第八部分

    第八部分内容:  1.正则化Regularization 2.在线学习(Online Learning) 3.ML 经验 1.正则化Regularization 1.1通俗解释 引用知乎作者:刑无刀 ...