标签: multiclass-classification

ValueError:无法处理多标签指标和二进制的混合

我将 Keras 与 scikit-learn 包装器一起使用。特别是,我想使用 GridSearchCV 进行超参数优化。

这是一个多类问题,即目标变量只能在一组 n 个类上选择一个标签。例如,目标变量可以是“Class1”、“Class2”...“Classn”。

# self._arch creates my model
nn = KerasClassifier(build_fn=self._arch, verbose=0)
clf = GridSearchCV(
  nn,
  param_grid={ ... },
  # I use f1 score macro averaged
  scoring='f1_macro',
  n_jobs=-1)

# self.fX is the data matrix
# self.fy_enc is the target variable encoded with one-hot format
clf.fit(self.fX.values, self.fy_enc.values)
Run Code Online (Sandbox Code Playgroud)

问题在于,在交叉验证期间计算分数时,验证样本的真实标签被编码为 one-hot,而由于某种原因,预测会折叠为二进制标签(当目标变量只有两个类时)。例如,这是堆栈跟踪的最后一部分:

...........................................................................
/Users/fbrundu/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/metrics/classification.py in _check_targets(y_true=array([[ 0.,  1.],
       [ 0.,  1.],
       [ 0... 0.,  1.],
       [ 0.,  1.],
       [ 0.,  1.]]), y_pred=array([1, 1, 1, 1, 1, 1, …
Run Code Online (Sandbox Code Playgroud)

scikit-learn keras grid-search one-hot-encoding multiclass-classification

4
推荐指数
1
解决办法
1万
查看次数

Keras二进制精度度量标准提供了太高的精度

我正在研究使用Keras的多类分类问题,我使用二进制精度和分类精度作为指标.当我评估我的模型时,我得到了一个非常高的二进制精度值和非常低的分类精度.我试图在我自己的代码中重新创建二进制精度指标,但我没有太多运气.我的理解是,这是我需要重新创建的过程:

def binary_accuracy(y_true, y_pred):
     return K.mean(K.equal(y_true, K.round(y_pred)), axis=-1)
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

from keras import backend as K
preds = model.predict(X_test, batch_size = 128)

print preds
pos = 0.00
neg = 0.00

for i, val in enumerate(roundpreds):

    if val.tolist() == y_test[i]:
        pos += 1.0

    else: 
        neg += 1.0

print pos/(pos + neg)
Run Code Online (Sandbox Code Playgroud)

但这比二进制精度给出的值低得多.二进制精度甚至是在多类问题中使用的适当度量吗?若有,那么有谁知道我哪里出错了?

classification machine-learning keras tensorflow multiclass-classification

4
推荐指数
1
解决办法
5362
查看次数

如何对Scikit-Learn中的训练和测试数据进行分层?

我正在尝试实现虹膜数据集的分类算法(从 Kaggle 下载)。在“物种”列中,类别(山鸢尾、杂色鸢尾、维吉尼亚鸢尾)按排序顺序排列。如何使用 Scikit-Learn 对训练数据和测试数据进行分层?

python machine-learning pandas scikit-learn multiclass-classification

4
推荐指数
1
解决办法
3854
查看次数

用于多类分类的 PyTorch LSTM:TypeError:“Example”和“Example”实例之间不支持“<”

我正在尝试修改本教程中的代码以使其适应多类数据(我有 55 个不同的类)。触发错误,但我不确定根本原因。我对本教程所做的更改已在同一行注释中进行了注释。

两个解决方案之一可以满足这个问题:

(A) 帮助确定错误的根本原因,或者

(B) 使用 PyTorch LSTM 进行多类分类的样板脚本

import spacy
import torchtext
from torchtext import data
import re

TEXT = data.Field(tokenize = 'spacy', include_lengths = True)
LABEL = data.LabelField(dtype = torch.float)
fields = [(None,None),('text', TEXT), ('wage_label', LABEL)]

train_torch, test_torch = data.TabularDataset.splits(path='/Users/jdmoore7/Desktop/Python Projects/560_capstone/', 
                                            format='csv', 
                                            train='train_text_target.csv', 
                                            test='test_text_target.csv', 
                                            fields=fields,
                                            skip_header=True)


import random
train_data, valid_data = train_torch.split(random_state = random.seed(SEED)) 

MAX_VOCAB_SIZE = 25_000

TEXT.build_vocab(train_data, 
                 max_size = MAX_VOCAB_SIZE, 
                 vectors = "glove.6B.100d", 
                 unk_init = torch.Tensor.normal_)

LABEL.build_vocab(train_data)

BATCH_SIZE = 64

device = torch.device('cuda' if …
Run Code Online (Sandbox Code Playgroud)

python lstm multiclass-classification pytorch

4
推荐指数
1
解决办法
2066
查看次数

在spacy中进行多类分类时出错

我正在尝试进行多类分类并使用crowdflower 文本分类数据集。以下是我的代码:

from __future__ import unicode_literals, print_function
from __future__ import unicode_literals

from pathlib import Path

import pandas as pd
import spacy
from spacy.util import minibatch, compounding




def main(model=None, output_dir=None, n_iter=20):
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank('en')  # create blank Language class
        print("Created blank 'en' model")

    # add the text classifier to the pipeline if it doesn't exist
    # nlp.create_pipe works for built-ins …
Run Code Online (Sandbox Code Playgroud)

python nlp spacy multiclass-classification

3
推荐指数
1
解决办法
1733
查看次数

在多类分类中,默认情况下,scikit-learn是否使用One-Vs-Rest?

我正在处理一个多类问题(4个类),并且试图通过python中的scikit-learn解决它。

我看到我有三个选择:

  1. 我只是实例化一个分类器,然后适合训练并通过测试进行评估;

    classifier = sv.LinearSVC(random_state=123)
    classifier.fit(Xtrain, ytrain)
    classifier.score(Xtest, ytest)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 我将实例化的分类器“封装”在OneVsRest对象中,生成一个新的分类器,用于训练和测试;

    classifier = OneVsRestClassifier(svm.LinearSVC(random_state=123))
    classifier.fit(Xtrain, ytrain)
    classifier.score(Xtest, ytest)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我将实例化的分类器“封装”在OneVsOne对象中,生成一个新的分类器,用于训练和测试。

    classifier = OneVsOneClassifier(svm.LinearSVC(random_state=123))
    classifier.fit(Xtrain, ytrain)
    classifier.score(Xtest, ytest)
    
    Run Code Online (Sandbox Code Playgroud)

我了解OneVsRest和OneVsOne之间的区别,但是我无法理解在第一种情况下我没有明确选择这两个选项中的任何一种。在这种情况下,scikit-learn会做什么?是否隐式使用OneVsRest?

对此事项的任何澄清将不胜感激。

最好,先生

编辑:只是为了弄清楚,我对SVM的情况并不特别感兴趣。例如,RandomForest呢?

python machine-learning scikit-learn multiclass-classification

3
推荐指数
1
解决办法
2202
查看次数

OneVsRestClassifier 可用于在 Python Scikit-Learn 中生成单独的二元分类器模型吗?

我正在阅读 Scikit-learn 的文档OneVsRestClassifier()链接。在我看来,OneVsRestClassifier 首先将多个类二值化为二进制类,然后训练模型,并对每个类重复。最后,它将分数“平均”为可以预测多个类别的最终 ML 模型。

对于我的示例,我有多类标签label1, label2, label3,但不是在最后进行总结,而是可以OneVsRestClassifier()迭代地为我提供二元分类。

我喜欢获得 3 个经过训练的 ML 模型。第一个是针对label1其余的 ( label2 and label3),第二个是针对label2其余的 ( label1 and label3),第三个是针对label3其余的 ( label1 and label2)。

我知道我可以手动二值化/二分结果标签,并运行二进制 ML 算法三次。但我想知道是否有OneVsRestClassifier()更好、更高效的能力来替代这种手工工作。

python-3.x scikit-learn multiclass-classification

3
推荐指数
1
解决办法
1275
查看次数

多类语义分割模型评估

我正在做一个关于多类语义分割的项目。我制定了一个模型,通过降低损失值来输出相当下降的分割图像。但是,我无法用指标来评估模型性能,例如meanIoU或Dice系数。在二元语义分割的情况下,只需设置 0.5 的阈值即可轻松将输出分类为对象或背景,但在多类语义分割的情况下则不起作用。您能告诉我如何获得上述指标的模型性能吗?任何帮助将不胜感激!

顺便说一句,我正在使用 PyTorch 框架和 CamVid 数据集。

image-segmentation python-3.x multiclass-classification pytorch semantic-segmentation

3
推荐指数
1
解决办法
8506
查看次数

如何在 Python 中创建混淆矩阵的图像

我是 Python 和机器学习的新手。我正在研究多类分类(3 个类)。我想将混淆矩阵保存为图像。现在,sklearn.metrics.confusion_matrix()帮助我找到混淆矩阵,如:

array([[35, 0, 6],
   [0, 0, 3],
   [5, 50, 1]])
Run Code Online (Sandbox Code Playgroud)

接下来,我想知道如何将这个混淆矩阵转换为图像并另存为png。

python machine-learning confusion-matrix scikit-learn multiclass-classification

3
推荐指数
1
解决办法
1669
查看次数

python中多类数据的正确率和错误率(TPR,FPR)

您如何计算多类别分类问题的正确率和错误率?说,

y_true = [1, -1,  0,  0,  1, -1,  1,  0, -1,  0,  1, -1,  1,  0,  0, -1,  0]
y_prediction = [-1, -1,  1,  0,  0,  0,  0, -1,  1, -1,  1,  1,  0,  0,  1,  1, -1]
Run Code Online (Sandbox Code Playgroud)

混淆矩阵由来计算metrics.confusion_matrix(y_true, y_prediction),但这只是解决了问题。


@seralouk的答案后编辑。在此,该类别-1应被视为否定词,而01是正值的变体。

python confusion-matrix scikit-learn multiclass-classification

2
推荐指数
1
解决办法
6994
查看次数