我需要的是:
- 应用逻辑回归分类器
- 使用 AUC 报告每个类的 ROC。
- 使用逻辑回归的估计概率来指导 ROC 的构建。
- 用于训练模型的 5 倍交叉验证。
为此,我的方法是使用这个非常好的教程:
根据他的想法和方法,我只是简单地改变了我获得原始数据的方式,我得到了这样的数据:
df = pd.read_csv(
filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
header=None,
sep=',')
df.columns=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class']
df.dropna(how="all", inplace=True) # drops the empty line at file-end
df.tail()
# split data table into data X and class labels y
X = df.iloc[:,0:4].values
Y = df.iloc[:,4].values
他们我只是运行代码。如果我尝试运行accuracy
或balanced_accuracy
等指标,一切
正常(即使使用许多其他指标也是如此)。我的问题是,当我尝试使用指标roc_auc
运行时,出现错误:
"值错误:y_true中仅存在一个类。ROC AUC 分数不是 在这种情况下定义。
此错误已在此处 1、此处 2、此处 3 和此处 4 中讨论。但是,我无法使用他们提供的任何"解决方案"/解决方法来解决我的问题。
我的整个代码是:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode
from sklearn.preprocessing import StandardScaler
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'qt')
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
df = pd.read_csv(
filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
header=None,
sep=',')
df.columns=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class']
df.dropna(how="all", inplace=True) # drops the empty line at file-end
df.tail()
# split data table into data X and class labels y
X = df.iloc[:,0:4].values
Y = df.iloc[:,4].values
#print(X)
#print(Y)
seed = 7
# prepare models
models = []
models.append(('LR', LogisticRegression()))
# evaluate each model in turn
results = []
names = []
scoring = 'roc_auc'
for name, model in models:
kfold = model_selection.KFold(n_splits=5, random_state=seed)
cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
# boxplot algorithm comparison
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.show()
鸢尾花数据集通常根据类进行排序。因此,当您拆分而不进行随机排序时,测试数据集可能只有一个类。
一个简单的解决方案是使用shuffle
参数。
kfold = model_selection.KFold(n_splits=10, shuffle=True, random_state=seed)
即便如此,roc_auc
也不直接支持多类格式(鸢尾花 - 数据集有三个类)。
通过此链接了解有关如何将roc_auc
用于多类情况的更多信息。
理想情况下,对于分类任务,使用分层 k 折叠迭代,以保持训练和测试折叠中类的平衡。
在scikit-learncross_val_score
中,交叉验证的默认行为取决于任务。文件说:-
cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are:
- 无,使用默认的 3 折交叉验证,
- 整数,用于指定(分层)KFold 中的折叠数, CV分路器,
可迭代的收益(训练、测试)拆分为索引数组。
对于整数/无输入,如果估计器是分类器,y 是二进制或多类,则使用 StratifiedKFold。在所有其他情况下,使用 KFold。
现在,鸢尾数据集是一组 150 个样本,按类别(Iris setosa、Iris virginica 和 Iris versicolor)排序。因此,使用 5 折的简单 K 折叠迭代器将处理训练集中的前 120 个样本和测试集中的最后 30 个样本。最后 30 个样本属于单个虹膜杂色类。
因此,如果您没有任何特定原因使用该KFold
,则可以这样做:
cv_results = model_selection.cross_val_score(model, X, Y, cv=5, scoring=scoring)
但现在来了scoring
的问题.您正在使用仅为二元分类任务定义的'roc_auc'
。因此,要么选择不同的指标来代替roc_auc
,要么指定要视为正数的类,将其他哪些类视为负数。