我对sklearn中的管道很新,我遇到了这个问题:我有一个混合了文本和数字的数据集,即某些列只有文本而rest有整数(或浮点数).
我想知道是否有可能构建一个管道,我可以调用LabelEncoder()文本功能和MinMaxScaler()数字列.我在网上看到的例子主要指向使用LabelEncoder()整个数据集而不是选择列.这可能吗?如果是这样,任何指针都将非常感激.
使用此作为垃圾邮件分类的模型时,我想添加主题和正文的附加功能.
我在熊猫数据框中拥有所有功能.例如,主题是df ['Subject'],正文是df ['body_text'],垃圾邮件/火腿标签是df ['ham/spam']
我收到以下错误:TypeError:'FeatureUnion'对象不可迭代
如何通过管道功能运行df ['Subject']和df ['body_text']作为功能?
from sklearn.pipeline import FeatureUnion
features = df[['Subject', 'body_text']].values
combined_2 = FeatureUnion(list(features))
pipeline = Pipeline([
('count_vectorizer', CountVectorizer(ngram_range=(1, 2))),
('tfidf_transformer', TfidfTransformer()),
('classifier', MultinomialNB())])
pipeline.fit(combined_2, df['ham/spam'])
k_fold = KFold(n=len(df), n_folds=6)
scores = []
confusion = numpy.array([[0, 0], [0, 0]])
for train_indices, test_indices in k_fold:
train_text = combined_2.iloc[train_indices]
train_y = df.iloc[test_indices]['ham/spam'].values
test_text = combined_2.iloc[test_indices]
test_y = df.iloc[test_indices]['ham/spam'].values
pipeline.fit(train_text, train_y)
predictions = pipeline.predict(test_text)
prediction_prob = pipeline.predict_proba(test_text)
confusion += confusion_matrix(test_y, predictions)
score = f1_score(test_y, predictions, …Run Code Online (Sandbox Code Playgroud) 我正在为网页编写分类器,所以我有多种数字特征,我也想对文本进行分类.我正在使用词袋方法将文本转换为(大)数字向量.代码最终是这样的:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
numerical_features = [
[1, 0],
[1, 1],
[0, 0],
[0, 1]
]
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one',
'Is this the first document?',
]
bag_of_words_vectorizer = CountVectorizer(min_df=1)
X = bag_of_words_vectorizer.fit_transform(corpus)
words_counts = X.toarray()
tfidf_transformer = TfidfTransformer()
tfidf = tfidf_transformer.fit_transform(words_counts)
bag_of_words_vectorizer.get_feature_names()
combinedFeatures = np.hstack([numerical_features, tfidf.toarray()])
Run Code Online (Sandbox Code Playgroud)
这有效,但我很关心准确性.请注意,有4个对象,只有两个数字特征.即使是最简单的文本也会产生具有九个特征的向量(因为语料库中有九个不同的单词).显然,对于真实文本,将会有数百个或数千个不同的单词,因此最终的特征向量将是<10个数字特征但是> 1000个单词的特征向量.
因此,分类器(SVM)不会将数字特征上的单词加权100到1倍吗?如果是这样,我该如何补偿以确保单词包的数量与数字特征的权重相等?