我有一个熊猫DataFrame
,包括文本的一列,我想矢量化文本使用scikit学习的CountVectorizer
。但是,文本包含缺失值,因此我想在矢量化之前估算一个常量值。
我最初的想法是创建一个Pipeline
的SimpleImputer
和CountVectorizer
:
import pandas as pd
import numpy as np
df = pd.DataFrame({'text':['abc def', 'abc ghi', np.nan]})
from sklearn.impute import SimpleImputer
imp = SimpleImputer(strategy='constant')
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer()
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(imp, vect)
pipe.fit_transform(df[['text']]).toarray()
Run Code Online (Sandbox Code Playgroud)
但是,fit_transform
错误是因为SimpleImputer
输出2D 数组并CountVectorizer
需要1D input。这是错误消息:
AttributeError: 'numpy.ndarray' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud)
问题:我该如何修改Pipeline
它才能使其正常工作?
注意:我知道我可以在 Pandas …
python machine-learning scikit-learn imputation countvectorizer
我为文本分析做了一个预处理部分,在删除停用词和词干后,如下所示:
test[col] = test[col].apply(
lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])
train[col] = train[col].apply(
lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])
Run Code Online (Sandbox Code Playgroud)
我有一个列有“清理词”列表的列。这是一列中的 3 行:
['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']
Run Code Online (Sandbox Code Playgroud)
我现在想将 CountVectorizer 应用于此列:
from …
Run Code Online (Sandbox Code Playgroud) 我有一个包含约 30k 个独特文档的数据集,这些文档被标记,因为它们中有某个关键字。数据集中的一些关键字段是文档标题、文件大小、关键字和摘录(关键字周围 50 个字)。这些约 30k 个唯一文档中的每一个都有多个关键字,并且每个文档在数据集中每个关键字都有一行(因此,每个文档都有多行)。以下是原始数据集中关键字段的示例:
我的目标是建立一个模型来标记某些事件(孩子们抱怨家庭作业等)的文档,因此我需要对关键字和摘录字段进行矢量化,然后将它们压缩,这样每个唯一文档就有一行。
仅使用关键字作为我要执行的操作的示例 - 我应用了 Tokenizer、StopWordsRemover 和 CountVectorizer,然后它们将输出一个带有计数矢量化结果的稀疏矩阵。一个稀疏向量可能类似于: sparseVector(158, {7: 1.0, 65: 1.0, 78: 2.0, 110: 1.0, 155: 3.0})
我想做两件事之一:
为了让您了解我的意思 - 下图左侧是 CountVectorizer 输出的所需密集向量表示,左侧是我想要的最终数据集。
所以我有以下标记化的列表:
tokenized_list = [['ALL', 'MY', 'CATS', 'IN', 'A', 'ROW'], ['WHEN', 'MY',
'CAT', 'SITS', 'DOWN', ',', 'SHE', 'LOOKS', 'LIKE', 'A',
'FURBY', 'TOY', '!'], ['THE', CAT', 'FROM', 'OUTER',
'SPACE'], ['SUNSHINE', 'LOVES', 'TO', 'SIT',
'LIKE', 'THIS', 'FOR', 'SOME', 'REASON', '.']]
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 CountVectorizer() 或 TfIdfVectorizer() 对其进行矢量化时
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
print(vectorizer.fit_transform(tokenized_list).todense())
print(vectorizer.vocabulary_)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
AttributeError: 'list' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud)
如果我在vectorizer.fit_transform()函数中放置一个简单的列表,它就可以正常工作。
我该如何消除这个错误?
我正在尝试使用向量化一些数据
sklearn.feature_extraction.text.CountVectorizer.
Run Code Online (Sandbox Code Playgroud)
这是我试图矢量化的数据:
corpus = [
'We are looking for Java developer',
'Frontend developer with knowledge in SQL and Jscript',
'And this is the third one.',
'Is this the first document?',
]
Run Code Online (Sandbox Code Playgroud)
矢量化器的属性由以下代码定义:
vectorizer = CountVectorizer(stop_words="english",binary=True,lowercase=False,vocabulary={'Jscript','.Net','TypeScript','SQL', 'NodeJS','Angular','Mongo','CSS','Python','PHP','Photoshop','Oracle','Linux','C++',"Java",'TeamCity','Frontend','Backend','Full stack', 'UI Design', 'Web','Integration','Database design','UX'})
Run Code Online (Sandbox Code Playgroud)
我运行后:
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(X.toarray())
Run Code Online (Sandbox Code Playgroud)
我得到了想要的结果,但词汇表中的关键字是按字母顺序排列的。输出如下所示:
['.Net', 'Angular', 'Backend', 'C++', 'CSS', 'Database design',
'Frontend', 'Full stack', 'Integration', 'Java', 'Jscript', 'Linux',
'Mongo', 'NodeJS', 'Oracle', 'PHP', 'Photoshop', 'Python', 'SQL',
'TeamCity', 'TypeScript', 'UI Design', 'UX', 'Web']
[
[0 0 0 …
Run Code Online (Sandbox Code Playgroud) 是否CountVectorizer
支持部分适合?
我想训练CountVectorizer
使用不同批次的数据。
CountVectorizer
并且CountVectorizerModel
经常创建一个稀疏特征向量,如下所示:
(10,[0,1,4,6,8],[2.0,1.0,1.0,1.0,1.0])
Run Code Online (Sandbox Code Playgroud)
这基本上表示词汇表的总大小为 10,当前文档有 5 个唯一元素,在特征向量中,这 5 个唯一元素的位置为 0、1、4、6 和 8。此外,其中一个元素显示上涨两倍,因此值为 2.0。
现在,我想“规范化”上述特征向量并使其看起来像这样,
(10,[0,1,4,6,8],[0.3333,0.1667,0.1667,0.1667,0.1667])
Run Code Online (Sandbox Code Playgroud)
即,每个值除以 6,即所有元素的总数。例如,0.3333 = 2.0/6
。
那么有没有一种方法可以有效地做到这一点呢?
谢谢!
在我的分类模型中,我需要维护大写字母,但是当我使用sklearn countVectorizer构建词汇表时,大写字母转换为小写!
为了排除隐式tokinization,我构建了一个标记器,它只传递文本而不进行任何操作..
我的代码:
co = dict()
def tokenizeManu(txt):
return txt.split()
def corpDict(x):
print('1: ', x)
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu)
countFit = count.fit_transform(x)
vocab = count.get_feature_names()
dist = np.sum(countFit.toarray(), axis=0)
for tag, count in zip(vocab, dist):
co[str(tag)] = count
x = ['I\'m John Dev', 'We are the only']
corpDict(x)
print(co)
Run Code Online (Sandbox Code Playgroud)
输出:
1: ["I'm John Dev", 'We are the only'] #<- before building the vocab.
{'john': 1, 'the': 1, 'we': 1, 'only': 1, 'dev': 1, "i'm": 1, 'are': 1} #<- …
Run Code Online (Sandbox Code Playgroud) 我想使用TFIDFVectorizer(或CountVectorizer后跟TFIDFTransformer)来获得我的术语的向量表示。这意味着,我想要一个术语的向量,其中文档是特征。这只是由 TFIDFVectorizer 创建的 TF-IDF 矩阵的转置。
>>> vectorizer = TfidfVectorizer()
>>> model = vectorizer.fit_transform(corpus)
>>> model.transpose()
Run Code Online (Sandbox Code Playgroud)
但是,我有 800k 个文档,这意味着我的术语向量非常稀疏且非常大(800k 维)。max_features
CountVectorizer 中的标志将完全符合我的要求。我可以指定一个维度,而 CountVectorizer 会尝试将所有信息放入该维度。不幸的是,这个选项是针对文档向量而不是词汇表中的术语。因此,它减少了我的词汇量,因为术语就是特征。
有什么办法可以做相反的事情吗?比如,在 TFIDFVectorizer 对象开始切割和规范化所有内容之前对其执行转置?如果存在这种方法,我该怎么做?像这样的东西:
>>> countVectorizer = CountVectorizer(input='filename', max_features=300, transpose=True)
Run Code Online (Sandbox Code Playgroud)
我一直在寻找这种方法,但每个指南、代码示例,无论是在谈论文档 TF-IDF 向量而不是术语向量。非常感谢您!
我正在尝试构建 ML 模型。但是,我很难理解在哪里应用编码。请参阅下面的步骤和功能来复制我一直遵循的过程。
首先,我将数据集拆分为训练和测试:
# Import the resampling package
from sklearn.naive_bayes import MultinomialNB
import string
from nltk.corpus import stopwords
import re
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
from sklearn.utils import resample
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
# Split into training and test sets
# Testing Count Vectorizer
X = df[['Text']]
y = df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=40)
# Returning to one dataframe
training_set = pd.concat([X_train, y_train], axis=1) …
Run Code Online (Sandbox Code Playgroud) python encoding machine-learning scikit-learn countvectorizer
countvectorizer ×10
python ×8
scikit-learn ×7
apache-spark ×2
tf-idf ×2
bag ×1
cpu-word ×1
encoding ×1
imputation ×1
nlp ×1
pandas ×1
pyspark ×1