我正在努力使用Scikit学习Python中的随机森林.我的问题是我用它进行文本分类(3个类 - 正/负/中性),我提取的特征主要是单词/ unigrams,所以我需要将它们转换为数字特征.我找到了一种方法做它DictVectorizer的fit_transform:
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer(sparse=False)
rf = RandomForestClassifier(n_estimators = 100)
trainFeatures1 = vec.fit_transform(trainFeatures)
# Fit the training data to the training output and create the decision trees
rf = rf.fit(trainFeatures1.toarray(), LabelEncoder().fit_transform(trainLabels))
testFeatures1 = vec.fit_transform(testFeatures)
# Take the same decision trees and run on the test data
Output = rf.score(testFeatures1.toarray(), LabelEncoder().fit_transform(testLabels))
print "accuracy: " + str(Output)
Run Code Online (Sandbox Code Playgroud)
我的问题是该fit_transform方法正在处理火车数据集,其中包含大约8000个实例,但是当我尝试将我的测试集转换为数字特征时,也就是大约80000个实例,我得到一个内存错误,说:
testFeatures1 = vec.fit_transform(testFeatures)
File …Run Code Online (Sandbox Code Playgroud) classification machine-learning random-forest scikit-learn text-classification
我使用scikit-learn Multinomial Naive Bayes分类器进行二进制文本分类(分类器告诉我文档是否属于X类).我使用平衡数据集训练我的模型和平衡测试集来测试它,结果很有希望.
该分类器需要实时运行并不断分析随机抛出的文档.
但是,当我在生产中运行我的分类器时,误报的数量非常高,因此我的精度非常低.原因很简单:在实时场景中(大约90%的时间),分类器会遇到更多负面样本,这与我用于测试和培训的理想平衡数据集不对应.
有没有办法可以在训练期间模拟这个实时案例,或者我可以使用任何技巧(包括对文档进行预处理以查看它们是否适合于分类器)?
我计划使用不平衡的数据集来训练我的分类器,其比例与我在实时案例中的比例相同,但我担心这可能会使朴素贝叶斯偏向负面阶级而失去对正面课程的回忆.
任何建议表示赞赏.
python classification machine-learning scikit-learn text-classification
我想在TfidfVectorizer中为stop_words添加一些单词.我按照添加单词的解决方案来scikit-learn的CountVectorizer的停止列表.我的停用词列表现在包含"英语"停用词和我指定的停用词.但是仍然TfidfVectorizer不接受我的停用词列表,我仍然可以在我的功能列表中看到这些词.以下是我的代码
from sklearn.feature_extraction import text
my_stop_words = text.ENGLISH_STOP_WORDS.union(my_words)
vectorizer = TfidfVectorizer(analyzer=u'word',max_df=0.95,lowercase=True,stop_words=set(my_stop_words),max_features=15000)
X= vectorizer.fit_transform(text)
Run Code Online (Sandbox Code Playgroud)
我还尝试在TfidfVectorizer中将stop_words设置为stop_words = my_stop_words.但它仍然无效.请帮忙.
python classification stop-words scikit-learn text-classification
在这个问题上,过去2-3周我一直在绞尽脑汁.我有一个多标签(不是多级)的问题,每个样品可以属于多个标签的.
我有大约450万个文本文档作为训练数据,大约100万个作为测试数据.标签大约35K.
我正在使用scikit-learn.对于特征提取我以前使用TfidfVectorizer它没有规模可言,我现在用的HashVectorizer这是更好的,但不是可扩展鉴于我有文件的数量.
vect = HashingVectorizer(strip_accents='ascii', analyzer='word', stop_words='english', n_features=(2 ** 10))
Run Code Online (Sandbox Code Playgroud)
SKlearn提供OneVsRestClassifier,我可以在其中提供任何估算器.对于多标签,我发现LinearSVC和SGDClassifier只能正常工作.根据我的基准,SGD在内存和时间方面都优于LinearSVC.所以,我有这样的事情
clf = OneVsRestClassifier(SGDClassifier(loss='log', penalty='l2', n_jobs=-1), n_jobs=-1)
Run Code Online (Sandbox Code Playgroud)
但是这有一些严重的问题:
classification machine-learning document-classification scikit-learn text-classification
我正在尝试FeatureUnion从数据结构中提取不同的功能,但由于尺寸不同而失败:ValueError: blocks[0,:] has incompatible row dimensions
我FeatureUnion的建立方式如下:
features = FeatureUnion([
('f1', Pipeline([
('get', GetItemTransformer('f1')),
('transform', vectorizer_f1)
])),
('f2', Pipeline([
('get', GetItemTransformer('f2')),
('transform', vectorizer_f1)
]))
])
Run Code Online (Sandbox Code Playgroud)
GetItemTransformer用于从同一结构中获取不同的数据部分.我们的想法是说明这里在scikit学习问题跟踪器.
结构本身存储{'f1': data_f1, 'f2': data_f2}在data_f1具有不同长度的不同列表的位置.
由于Y-Vector与数据字段不同,我假设发生了错误,但是如何缩放矢量以适应两种情况?
我正在尝试使用 Hugging Face 'Transformers' 库提供的不同转换器架构对自定义数据(采用 csv 格式)进行二进制文本分类。我正在使用这篇Tensorflow 博客文章作为参考。
我正在使用以下代码将自定义数据集加载为“tf.data.Dataset”格式:
def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=5, # Artificially small to make examples easier to show.
na_value="",
num_epochs=1,
ignore_errors=True,
**kwargs)
return dataset
Run Code Online (Sandbox Code Playgroud)
在此之后,当我尝试使用“glue_convert_examples_to_features”方法进行标记化时,如下所示:
train_dataset = glue_convert_examples_to_features(
examples = train_data,
tokenizer = tokenizer,
task = None,
label_list = ['0', '1'],
max_length = 128
)
Run Code Online (Sandbox Code Playgroud)
在以下位置引发错误“UnboundLocalError:分配前引用的局部变量‘处理器’”:
if is_tf_dataset:
example = processor.get_example_from_tensor_dict(example)
example = processor.tfds_map(example)
Run Code Online (Sandbox Code Playgroud)
在所有示例中,我看到他们正在使用诸如“mrpc”之类的任务,这些任务是预定义的并且有一个glue_processor 来处理。在源代码中的“第 85 行”处引发错误。
任何人都可以使用“自定义数据”帮助解决此问题吗?
python text-classification tensorflow huggingface-transformers
我有一个一维数组,每个元素都有大字符串.我试图使用a CountVectorizer将文本数据转换为数字向量.但是,我收到一个错误说:
AttributeError: 'numpy.ndarray' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud)
mealarray每个元素中包含大字符串.有5000个这样的样本.我正在尝试对此进行矢量化,如下所示:
vectorizer = CountVectorizer(
stop_words='english',
ngram_range=(1, 1), #ngram_range=(1, 1) is the default
dtype='double',
)
data = vectorizer.fit_transform(mealarray)
Run Code Online (Sandbox Code Playgroud)
完整的堆栈跟踪:
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform
self.fixed_vocabulary_)
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 748, in _count_vocab
for feature in analyze(doc):
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 234, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 200, in <lambda>
return lambda x: strip_accents(x.lower())
AttributeError: 'numpy.ndarray' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud) 是否有一个很好的McNemar测试在Python中实现?我没有在Scipy.stats或Scikit-Learn中看到它.我可能忽略了其他一些好的套餐.请推荐.
McNemar的测试几乎是用于比较给定保持测试集的两种分类算法/模型的测试(不是通过K折叠或重采样方法来模拟测试集).两种常见的替代方案是:用于比较直接真实正比例p_A和p_B来自两种算法和模型的t检验,A以及B1)假设方差遵循二项分布或2)使用重复重采样序列和测试集来估计方差.
然而,后两者显示具有高的1型错误(声明模型在统计上不同但实质上它们是相同的).如果比较两种分类算法或模型,McNemar的测试仍被认为是最好的.见Dietterich10.
或者作为替代方案,如果不是通过McNemar的测试,人们如何在实践中统计比较两种分类模型?
python statistics classification machine-learning text-classification
以前的实现:应用弹性搜索但精度非常低,因为用户输入任何文本,如"我需要"=="想要"
数据集信息:数据集包含每一行,文本(或段落)和标签(作为页码).这里数据集大小很小,我只有500行.
Applied NLP for,
结果:测试数据(或验证数据)的准确率为23%,但列车数据为91%
import time
from time import strftime
import numpy as np
from keras.callbacks import CSVLogger, ModelCheckpoint
from keras.layers import Dense, Input, LSTM, ActivityRegularization
from keras.layers import Embedding, Dropout,Bidirectional
from keras.models import Model
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.regularizers import l2
from keras.utils import to_categorical
import pickle
from DataGenerator import *
BASE_DIR …Run Code Online (Sandbox Code Playgroud) 我想使用 word2vec 执行文本分类。我得到了词向量。
ls = []
sentences = lines.split(".")
for i in sentences:
ls.append(i.split())
model = Word2Vec(ls, min_count=1, size = 4)
words = list(model.wv.vocab)
print(words)
vectors = []
for word in words:
vectors.append(model[word].tolist())
data = np.array(vectors)
data
Run Code Online (Sandbox Code Playgroud)
输出:
array([[ 0.00933912, 0.07960335, -0.04559333, 0.10600036],
[ 0.10576613, 0.07267512, -0.10718666, -0.00804013],
[ 0.09459028, -0.09901826, -0.07074171, -0.12022413],
[-0.09893986, 0.01500741, -0.04796079, -0.04447284],
[ 0.04403428, -0.07966098, -0.06460238, -0.07369237],
[ 0.09352681, -0.03864434, -0.01743148, 0.11251986],.....])
Run Code Online (Sandbox Code Playgroud)
我如何进行分类(产品和非产品)?
python ×6
scikit-learn ×6
tensorflow ×2
gensim ×1
keras ×1
lstm ×1
numpy ×1
python-3.x ×1
statistics ×1
stop-words ×1
word2vec ×1