问题描述
要打印具有多个模型的ROC曲线,我面临着这个特殊错误。需要帮助
from tensorflow.keras.models import load_model
def dense():
return (load_model('DenseNet201.h5'))
def mobile():
return(load_model('MobileNet.h5'))
def res():
return(load_model('resnet50V2.h5'))
def vgg():
return(load_model('VGG16.h5'))
models = [
{
'label': 'DenseNet201','model': dense(),},{
'label': 'MobileNet','model':mobile(),{
'label': 'resnet50V2','model':res(),{
'label': 'VGG16','model':vgg(),}]
from sklearn import metrics
import matplotlib.pyplot as plt
from tensorflow.keras.utils import to_categorical
plt.figure()
# Below for loop iterates through your models list
for m in models:
model = m['model'] # select the model
#model.fit(X_train,y_train) # train the model
y_pred=model.predict(X_test) # predict the test data
# Compute False postive rate,and True positive rate
#fpr,tpr,thresholds = metrics.roc_curve(y_test,model.y_pred_bin(X_test)[:,1])
fpr,model.predict_proba(X_test)[:,1])
# Calculate Area under the curve to display on the plot
auc = metrics.roc_auc_score(y_test,model.predict(X_test))
# Now,plot the computed values
plt.plot(fpr,label='%s ROC (area = %0.2f)' % (m['label'],auc))
# Custom settings for the plot
plt.plot([0,1],[0,'r--')
plt.xlim([0.0,1.0])
plt.ylim([0.0,1.05])
plt.xlabel('1-Specificity(False Positive Rate)')
plt.ylabel('Sensitivity(True Positive Rate)')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show() # display
我将预训练的模型加载到函数中,并使用此代码将其返回。我列出了要迭代的列表,它将调用加载这些模型的函数,因此将绘制每个模型的ROC曲线。
完整TraceBack
> AttributeError Traceback (most recent call
> last) <ipython-input-43-f353a6208636> in <module>()
> 11 # Compute False postive rate,and True positive rate
> 12 #fpr,1])
> ---> 13 pred_prob = model.predict_proba(X_test)
> 14 fpr,pred_prob[:,1])
> 15 # Calculate Area under the curve to display on the plot
>
> AttributeError: 'Functional' object has no attribute 'predict_proba'
解决方法
你可以改用这个 -
model.predict_on_batch(X_test)
请注意,roc_curve 或 f1_score 仅采用单值输出。像 [[1],[0],....[1]]
在我的情况下,我已将其转换为分类,例如 [[0,1],[1,0],...,[0,1]] ,并在我的输出中使用了 softmax
so model.predict_on_batch(X_test) 也给出了输出 likr [[0.3,0.7],[0.9,0.1] ...[0.2,0.8]]
所以我必须将其转换为单值输出,然后使用以下函数将其传递给 sklearn 的 roc_curve 或 f1_score:
def y_(y):
r = []
for i in y:
if i[0] > 0.5:
r.append([0])
else:
r.append([1])
return np.array(r)