我想使用 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)
我如何进行分类(产品和非产品)?
我正在尝试从以下存储库中获取代码,该存储库基于本文。它有很多错误,但我主要让它工作。但是,我一直遇到同样的问题,我真的不明白如何解决这个问题/甚至出了什么问题。
第二次验证是否满足语句标准时发生错误。第一次总是有效,然后在第二次中断。如果有帮助,我将包括它在中断之前打印的输出。请参阅下面的错误:
step = 1, train_loss = 1204.7784423828125, train_accuracy = 0.13725490868091583
counter = 1, dev_loss = 1188.6639287274584, dev_accuacy = 0.2814199453625912
step = 2, train_loss = 1000.983154296875, train_accuracy = 0.26249998807907104
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _do_call(self, fn, *args)
1364 try:
-> 1365 return fn(*args)
1366 except errors.OpError as e:
7 frames
InvalidArgumentError: 2 root error(s) found.
(0) Invalid argument: Incompatible shapes: [2,185] vs. [2,229]
[[{{node loss/cond/add_1}}]]
[[viterbi_decode/cond/rnn_1/while/Switch_3/_541]]
(1) Invalid argument: Incompatible shapes: [2,185] …Run Code Online (Sandbox Code Playgroud)我在原始文本中有大量的意见(2500).我想使用scikit-learn库将它们分成测试/训练集.用scikit-learn解决这个任务可能是最好的方法吗?任何人都可以给我一个在测试/训练集中拆分原始文本的例子(可能我会使用tf-idf表示).
classification machine-learning scikit-learn cross-validation text-classification
我在Keras使用路透社数据集.
我想知道46个主题的名字.
如何在Keras中显示路透社数据集的主题?
https://keras.io/datasets/#reuters-newswire-topics-classification
我正在做不同的文本分类实验.现在我需要计算每项任务的AUC-ROC.对于二进制分类,我已经使用此代码:
scaler = StandardScaler(with_mean=False)
enc = LabelEncoder()
y = enc.fit_transform(labels)
feat_sel = SelectKBest(mutual_info_classif, k=200)
clf = linear_model.LogisticRegression()
pipe = Pipeline([('vectorizer', DictVectorizer()),
('scaler', StandardScaler(with_mean=False)),
('mutual_info', feat_sel),
('logistregress', clf)])
y_pred = model_selection.cross_val_predict(pipe, instances, y, cv=10)
# instances is a list of dictionaries
#visualisation ROC-AUC
fpr, tpr, thresholds = roc_curve(y, y_pred)
auc = auc(fpr, tpr)
print('auc =', auc)
plt.figure()
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b',
label='AUC = %0.2f'% auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.1,1.2])
plt.ylim([-0.1,1.2])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
Run Code Online (Sandbox Code Playgroud)
但现在我需要为多类分类任务执行此操作.我读到了我需要对标签进行二值化的地方,但我真的不知道如何计算多类分类的ROC.提示?
python roc scikit-learn text-classification multiclass-classification
我正在使用 TFIDF 稀疏矩阵进行文档分类,并且希望仅保留每个文档的前 n 个(比如 50 个)术语(按 TFIDF 分数排名)。请参阅下面的编辑。
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
tfidfvectorizer = TfidfVectorizer(analyzer='word', stop_words='english',
token_pattern='[A-Za-z][\w\-]*', max_df=0.25)
n = 50
df = pd.read_pickle('my_df.pickle')
df_t = tfidfvectorizer.fit_transform(df['text'])
df_t
Out[15]:
<21175x201380 sparse matrix of type '<class 'numpy.float64'>'
with 6055621 stored elements in Compressed Sparse Row format>
Run Code Online (Sandbox Code Playgroud)
我已经尝试按照这篇文章中的示例进行操作,虽然我的目的不是显示特征,而是在训练前为每个文档选择前 n 个。但是我收到内存错误,因为我的数据太大而无法转换为密集矩阵。
df_t_sorted = np.argsort(df_t.toarray()).flatten()[::1][n]
Traceback (most recent call last):
File "<ipython-input-16-e0a74c393ca5>", line 1, in <module>
df_t_sorted = np.argsort(df_t.toarray()).flatten()[::1][n]
File "C:\Users\Me\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\sparse\compressed.py", …Run Code Online (Sandbox Code Playgroud) python sparse-matrix tf-idf scikit-learn text-classification
我正在尝试开发一个文本分类器,将一个文本分类为Private或Public。以医疗或健康信息为例。我可以想到的典型分类器将关键字视为主要的区分符,对吗?像波纹管这样的场景呢?如果两条文本都包含相似的关键字但含义不同,该怎么办。
以下文字揭示了某人的私人(健康)状况(患者患有癌症):
我去过两个clinics和我的pcp。我ultrasound只能被告知这是一个解决方案cyst或解决方案hematoma,但是它越来越大,开始使我的腿变大ache。之所以PCP说不能,是cyst因为它起步太大,我发誓injured我的腿永远都没有,甚至没有bump。我现在感到害怕和恐惧cancer。仅在大约9个月前蹲下时,我才感到有点不适。3个月前我去蹲下收起衣服,有点麻烦hurt。在pain促使我开始审视自己leg,这是当我注意到lump在我小腿的底部muscle和弯曲只有变得更加明显。最终在四次clinic拜访之后,一个ultrasound和一个pcp结果似乎是积极的,而且人数越来越大。
[私人](正确分类)
接下来的一段文字是医生的评论,绝对没有透露健康状况。它介绍了典型分类器模型的缺点:
不要害怕,不要承担任何坏事cancer。我已经经历了几次案件,对我clinic来说似乎很熟悉。正如您提到的,它可能是a cyst或a hematoma,并且越来越大,它必须需要一些其他字符,diagnosis例如biopsy。有一个ache在该领域或的大小lump并没有真正告诉任何东西bad。你应该访问专门clinics几次,并且在某些特定的测试,如走biopsy,CT scan,pcp而ultrasound在此之前,lump变得更加大。
[私人](分类错误。应为[公开]) …
我正在使用 sklearn 的线性 SVC 模型进行文本分类。现在我想使用 SHAP ( https://github.com/slundberg/shap )可视化哪些单词/标记对分类决策影响最大。
现在这不起作用,因为我收到一个错误,该错误似乎源自我定义的管道中的矢量化步骤 - 这里出了什么问题?
我在这种情况下使用 SHAP 的一般方法是否正确?
x_Train, x_Test, y_Train, y_Test = train_test_split(df_all['PDFText'], df_all['class'], test_size = 0.2, random_state = 1234)
pipeline = Pipeline([
(
'tfidv',
TfidfVectorizer(
ngram_range=(1,3),
analyzer='word',
strip_accents = ascii,
use_idf = True,
sublinear_tf=True,
max_features=6000,
min_df=2,
max_df=1.0
)
),
(
'lin_svc',
svm.SVC(
C=1.0,
probability=True,
kernel='linear'
)
)
])
pipeline.fit(x_Train, y_Train)
shap.initjs()
explainer = shap.KernelExplainer(pipeline.predict_proba, x_Train)
shap_values = explainer.shap_values(x_Test, nsamples=100)
shap.force_plot(explainer.expected_value[0], shap_values[0][0,:], x_Test.iloc[0,:])
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误消息:
Provided model function fails when applied to …Run Code Online (Sandbox Code Playgroud) 如果我想使用sklearn库实现分类器。有没有办法保存模型或将文件转换为已保存的tensorflow文件以便tensorflow lite以后将其转换?
machine-learning scikit-learn text-classification tensorflow tensorflow-lite
我有一个数据集并尝试使用 berTopic 建模将其转换为主题,但问题是,我无法获取主题的所有文档。berTopic 每个主题仅返回 3 个文档。
topic_model = BERTopic(verbose=True, embedding_model=embedding_model,
nr_topics = 'auto',
n_gram_range = (3,3),
top_n_words = 10,
calculate_probabilities=True,
seed_topic_list = topic_list,
)
topics, probs = topic_model.fit_transform(docs_test)
representative_doc = topic_model.get_representative_docs(topic#1)
representative_doc
Run Code Online (Sandbox Code Playgroud)
该主题包含超过 300 个文档,但 bertopic 仅显示其中 3 个.get_representative_docs
scikit-learn ×5
python ×4
nlp ×3
tensorflow ×2
gensim ×1
keras ×1
natural-language-processing ×1
pipeline ×1
python-3.x ×1
roc ×1
shap ×1
svc ×1
tf-idf ×1
word2vec ×1