我正在研究一个多类文本分类问题,该问题需要具有相应概率的前3个预测标签。我能够使用sklearn predict_proba()
,但是很难像表a那样格式化输出。我的代码如下:
cv = StratifiedKFold(n_splits = 10, random_state = 42, shuffle = None)
pipeline_sgd = Pipeline([
('vect', CountVectorizer()),
('tfdif', TfidfTransformer()),
('nb', CalibratedClassifierCV(base_estimator = SGDClassifier(), cv=cv)),
])
Model = pipeline_sgd.fit(X_train, y_train)
n_top_labels = 3
probas = model.predict_probas(test["text"])
top_n_lables_idx = probas.argsort()[::-1][:n_top_lables]
top_n_probs = probas[top_n_lables_idx]
top_n_labels = label_encoder.inverse_transform(top_n_lables_idx.ravel())
results = list(zip(top_n_labels, top_n_probas))
输出:
[(A, .80),
(B, .10),
(C, .10)]
我对上述输出的挑战是,它没有为每行文本提供前3个标签/概率。例如,当我对一组新文档(文本)运行推断时,我只得到一个输出,而不是每个文档(行)的一个输出
我面临的第二个挑战是,当我使用pd.Dataframe(data = results)
将其插入数据帧时,我得到以下结果:
| | 0 | 1 |
|---|---|-----------------|
| 0 | A | [[.80,.10,.10]] |
| 1 | B | [[.85,.10,.05]] |
| 2 | C | [[.70,.20,.10]] |
应该是:
| | 0 | 1 |
|---|-------|-----------------|
| 0 | A,B,C | [[.80,.10,.10]] |
| 1 | B,C,A | [[.85,.10,.05]] |
| 2 | C,B,A | [[.70,.20,.10]] |
表A
| Text | Predicted labels | Probabilities |
|--------------------------------------------|------------------|----------------|
| Hello World! | A,B,C | [.80,.10,10] |
| Have a nice Day! | B,C,A | [.90,.05,05] |
| It's a wonderful day in the neighborhood. | C,A,B | [.80,.10,10] |
更新到已接受的答案
这确保了我在两列中都获得了前3名
当我运行你的代码时,我有一个非常奇怪的
top_n_probs
形状,我发现很难找回标签。用于调用排序值的argsort
和代码似乎有点奇怪下面我写了一个应该可以工作的快速实现
使用示例dataset:
我的标签如下所示:
并运行代码进行安装:
这应该起作用:
相关问题 更多 >
编程相关推荐