如果我错了,请纠正我:scikit-learn的roc_curve返回的"阈值"应该是[0,1]中的数字数组.但是,它有时会给我一个第一个数字接近"2"的数组.这是一个错误还是我做错了?谢谢.
In [1]: import numpy as np
In [2]: from sklearn.metrics import roc_curve
In [3]: np.random.seed(11)
In [4]: aa = np.random.choice([True, False],100)
In [5]: bb = np.random.uniform(0,1,100)
In [6]: fpr,tpr,thresholds = roc_curve(aa,bb)
In [7]: thresholds
Out[7]:
array([ 1.97396826, 0.97396826, 0.9711752 , 0.95996265, 0.95744405,
0.94983331, 0.93290463, 0.93241372, 0.93214862, 0.93076592,
0.92960511, 0.92245024, 0.91179548, 0.91112166, 0.87529458,
0.84493853, 0.84068543, 0.83303741, 0.82565223, 0.81096657,
0.80656679, 0.79387241, 0.77054807, 0.76763223, 0.7644911 ,
0.75964947, 0.73995152, 0.73825262, 0.73466772, 0.73421299,
0.73282534, 0.72391126, 0.71296292, 0.70930102, 0.70116428,
0.69606617, 0.65869235, 0.65670881, 0.65261474, 0.6487222 , …Run Code Online (Sandbox Code Playgroud) 我使用了caret包的train函数和10倍交叉验证.我还设置了某个类的概率预测类classProbs = TRUE中trControl,如下所示:
myTrainingControl <- trainControl(method = "cv",
number = 10,
savePredictions = TRUE,
classProbs = TRUE,
verboseIter = TRUE)
randomForestFit = train(x = input[3:154],
y = as.factor(input$Target),
method = "rf",
trControl = myTrainingControl,
preProcess = c("center","scale"),
ntree = 50)
Run Code Online (Sandbox Code Playgroud)
我得到的输出预测如下.
pred obs 0 1 rowIndex mtry Resample
1 0 1 0.52 0.48 28 12 Fold01
2 0 0 0.58 0.42 43 12 Fold01
3 0 1 0.58 0.42 51 12 Fold01 …Run Code Online (Sandbox Code Playgroud) 我正在做不同的文本分类实验.现在我需要计算每项任务的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
我写了一个分类器(高斯混合模型)来分类五个人类行为.对于每次观察,分类器计算属于群集的后验概率.
我想要用阈值参数化我的系统的性能,值为0到100.对于每个阈值,对于每个观察,如果属于一个簇的概率大于阈值,我接受分类器的结果否则我丢弃它.
对于每个阈值,我计算真阳性,真阴性,假阳性,假阴性的数量.
比我计算两个函数:灵敏度和特异性为
sensitivity = TP/(TP+FN);
specificity=TN/(TN+FP);
Run Code Online (Sandbox Code Playgroud)
在matlab中:
plot(1-specificity,sensitivity);
Run Code Online (Sandbox Code Playgroud)
有ROC曲线.但结果并不是我所期望的.
这是丢弃,错误,纠正,敏感性和特异性功能的图,改变了一个动作的阈值.

这是一个动作的ROC曲线图

这是同一动作的ROC曲线的主干

我错了,但我不知道在哪里.也许我错误地计算了FP,FN,TP,TN,特别是当分类器的结果小于阈值时,所以我丢弃了.当丢弃时我必须增加什么?
我试图绘制多类ROC曲线,但我没有在pROC包中找到任何有效的东西.这是一些开始代码:
data(iris)
library(randomForest)
library(pROC)
set.seed(1000)
# 3-class in response variable
rf = randomForest(Species~., data = iris, ntree = 100)
# predict(.., type = 'prob') returns a probability matrix
predictions <- as.numeric(predict(rf, iris, type = 'response'))
roc.multi <- multiclass.roc(iris$Species, predictions)
auc(roc.multi)
Run Code Online (Sandbox Code Playgroud)
如何绘制各个类的ROC曲线?
我使用Tensorflow构建了一个二元分类器,现在我想用AUC和准确度来评估分类器.
就准确性而言,我可以轻松地这样做:
X = tf.placeholder('float', [None, n_input])
y = tf.placeholder('float', [None, n_classes])
pred = mlp(X, weights, biases, dropout_keep_prob)
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
Run Code Online (Sandbox Code Playgroud)
在计算AUC时,我使用以下内容:
print(tf.argmax(pred, 1).dtype.name)
print(tf.argmax(pred, 1).dtype.name)
a = tf.cast(tf.argmax(pred, 1),tf.float32)
b = tf.cast(tf.argmax(y,1),tf.float32)
auc = tf.contrib.metrics.streaming_auc(a, b)
Run Code Online (Sandbox Code Playgroud)
并在训练循环中:
train_acc = sess.run(accuracy, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
train_auc = sess.run(auc, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
Run Code Online (Sandbox Code Playgroud)
这给了我以下输出(和错误)错误:
int64
int64
/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/array_ops.py:1197: VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an …Run Code Online (Sandbox Code Playgroud) 我已经安装了SVM模型,并使用ROCR包创建了ROC曲线。如何计算曲线下面积(AUC)?
set.seed(1)
tune.out=tune(svm ,Negative~.-Positive, data=trainSparse, kernel ="radial",ranges=list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4) ))
summary(tune.out)
best=tune.out$best.model
##prediction on the test set
ypred = predict(best,testSparse, type = "class")
table(testSparse$Negative,ypred)
###Roc curve
yhat.opt = predict(best,testSparse,decision.values = TRUE)
fitted.opt = attributes(yhat.opt)$decision.values
rocplot(fitted.opt,testSparse ["Negative"], main = "Test Data")##
Run Code Online (Sandbox Code Playgroud) 我正在建造2个模型.
模型1
modelgb = GradientBoostingClassifier()
modelgb.fit(x_train,y_train)
predsgb = modelgb.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predsgb, average='macro', sample_weight=None)
Run Code Online (Sandbox Code Playgroud)
模型2
model = LogisticRegression()
model = model.fit(x_train,y_train)
predslog = model.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predslog, average='macro', sample_weight=None)
Run Code Online (Sandbox Code Playgroud)
如何在一个图中绘制两个ROC曲线,每个模型的AUC分数的图例和文本?
roc_curve我有一个与深度学习练习相关的问题scikit-learn,我注意到我的数据有 1 作为正标签。经过我的训练,测试准确率约为 74%,但 roc 曲线下面积 (AUC) 分数仅为 0.24。
y_pred = model.predict([x_test_real[:, 0],x_test_real[:, 1]])
fpr, tpr, thresholds = metrics.roc_curve(y_test_real, y_pred,pos_label=1)
roc_auc = metrics.auc(fpr, tpr)
print("roc_auc: %0.2f" % roc_auc)
Run Code Online (Sandbox Code Playgroud)
如果我将 更改pos_label为 0。auc 分数变为 0.76(显然)
y_pred = model.predict([x_test_real[:, 0],x_test_real[:, 1]])
fpr, tpr, thresholds = metrics.roc_curve(y_test_real, y_pred,pos_label=0)
roc_auc = metrics.auc(fpr, tpr)
print("roc_auc: %0.2f" % roc_auc)
Run Code Online (Sandbox Code Playgroud)
现在我做了一个小实验,我改变了我的训练和测试标签(这是二元分类)
y_train_real = 1 - y_train_real
y_test_real = 1 - y_test_real
Run Code Online (Sandbox Code Playgroud)
像这样,这应该将正标签和负标签从 1 翻转到 0。然后我再次运行我的代码。这次预计大鹏 auc 的行为也会发生翻转。但不是!
fpr, tpr, thresholds = metrics.roc_curve(y_test_real, y_pred,pos_label=0) …Run Code Online (Sandbox Code Playgroud) 我randomForest在R平台上使用包进行分类任务.
rf_object<-randomForest(data_matrix, label_factor, cutoff=c(k,1-k))
Run Code Online (Sandbox Code Playgroud)
其中k的范围为0.1至0.9.
pred <- predict(rf_object,test_data_matrix)
Run Code Online (Sandbox Code Playgroud)
我有随机森林分类器的输出,我将它与标签进行了比较.因此,我有9个截止点的准确度,MCC,灵敏度,特异性等性能指标.
现在,我想绘制ROC曲线并获得ROC曲线下的面积,看看性能有多好.R中的大多数包(如ROCR,pROC)需要预测和标记,但我有灵敏度(TPR)和特异性(1-FPR).
任何人都可以建议我,如果截止方法是正确的还是可靠的,以产生ROC曲线?您是否知道使用TPR和FPR获得ROC曲线和曲线下面积的方法?
我还尝试使用以下命令来训练随机森林.通过这种方式,预测是连续的,ROCR并且pROC在R 中可以接受并打包.但是,我不确定这是否是正确的方法.任何人都可以向我推荐这种方法吗?
rf_object <- randomForest(data_matrix, label_vector)
pred <- predict(rf_object, test_data_matrix)
Run Code Online (Sandbox Code Playgroud)
感谢您抽出时间阅读我的问题!我花了很长时间冲浪.感谢您的建议/意见.
roc ×10
auc ×4
r ×4
python ×3
scikit-learn ×3
keras ×1
matlab ×1
plot ×1
python-3.5 ×1
r-caret ×1
tensorflow ×1
threshold ×1