我刚开始学习Python中的机器学习,所以请原谅我的问题。我想知道是否有Python库可以实现神经网络,并且能够提供ROC和AUC曲线。我知道Python中有实现神经网络的库,但我正在寻找一个可以帮助我绘制ROC、DET和AUC曲线的库。
回答:
在这种情况下,最好将您的问题分为两个主题,因为神经网络与ROC曲线几乎没有直接关系。
神经网络
我认为通过示例学习是最好的方法,所以我将展示一个使用二分类问题训练的前馈神经网络的方法,这个方法受到这个教程的启发,来自pybrain。
首先需要定义一个数据集。最容易可视化的方法是使用二维平面上的二分类数据集,数据点从正态分布中生成,每个点属于两个类别之一。在这种情况下,这将是线性可分的。
from pybrain.datasets import ClassificationDataSetfrom pybrain.utilities import percentErrorfrom pybrain.tools.shortcuts import buildNetworkfrom pybrain.supervised.trainers import BackpropTrainerfrom pybrain.structure.modules import SoftmaxLayerfrom pylab import ion, ioff, figure, draw, contourf, clf, show, hold, plotfrom scipy import diag, arange, meshgrid, wherefrom numpy.random import multivariate_normalmeans = [(-1,0),(2,4),(3,1)]cov = [diag([1,1]), diag([0.5,1.2]), diag([1.5,0.7])]n_klass = 2alldata = ClassificationDataSet(2, 1, nb_classes=n_klass)for n in xrange(400): for klass in range(n_klass): input = multivariate_normal(means[klass],cov[klass]) alldata.addSample(input, [klass])
可视化后,它看起来像这样:
现在您需要将数据集分为训练集和测试集:
tstdata, trndata = alldata.splitWithProportion(0.25)trndata._convertToOneOfMany()tstdata._convertToOneOfMany()
然后创建您的网络:
fnn = buildNetwork( trndata.indim, 5, trndata.outdim, outclass=SoftmaxLayer )trainer = BackpropTrainer( fnn, dataset=trndata, momentum=0.1, verbose=True, weightdecay=0.01)ticks = arange(-3.,6.,0.2)X, Y = meshgrid(ticks, ticks)# need column vectors in dataset, not arraysgriddata = ClassificationDataSet(2,1, nb_classes=n_klass)for i in xrange(X.size): griddata.addSample([X.ravel()[i],Y.ravel()[i]], [0])griddata._convertToOneOfMany() # this is still needed to make the fnn feel comfy
现在您需要训练您的网络并查看最终的结果:
for i in range(20): trainer.trainEpochs( 1 ) trnresult = percentError( trainer.testOnClassData(), trndata['class'] ) tstresult = percentError( trainer.testOnClassData( dataset=tstdata ), tstdata['class'] ) print "epoch: %4d" % trainer.totalepochs, \ " train error: %5.2f%%" % trnresult, \ " test error: %5.2f%%" % tstresult out = fnn.activateOnDataset(griddata) out = out.argmax(axis=1) # the highest output activation gives the class out = out.reshape(X.shape) figure(1) ioff() # interactive graphics off clf() # clear the plot hold(True) # overplot on for c in range(n_klass): here, _ = where(tstdata['class']==c) plot(tstdata['input'][here,0],tstdata['input'][here,1],'o') if out.max()!=out.min(): # safety check against flat field contourf(X, Y, out) # plot the contour ion() # interactive graphics on draw() # update the plot
开始时边界非常差:
但最终结果相当好:
ROC曲线
关于ROC曲线,这里有一个简单易用的Python库,可以在随机玩具问题上使用:
from pyroc import *random_sample = random_mixture_model() # Generate a custom set randomly#Example instance labels (first index) with the decision function , score (second index)#-- positive class should be +1 and negative 0.roc = ROCData(random_sample) #Create the ROC Objectroc.auc() #get the area under the curveroc.plot(title='ROC Curve') #Create a plot of the ROC curve
这将为您提供一个单一的ROC曲线:
当然,您也可以在同一图表上绘制多个ROC曲线:
x = random_mixture_model()r1 = ROCData(x)y = random_mixture_model()r2 = ROCData(y)lista = [r1,r2]plot_multiple_roc(lista,'Multiple ROC Curves',include_baseline=True)
(请记住,对角线意味着您的分类器是随机的,您可能做错了什么)
您可以轻松地在任何分类任务中使用这些模块(不限于神经网络),它将为您生成ROC曲线。
现在,要从您的神经网络中获取绘制ROC曲线所需的类/概率,您只需查看神经网络的激活情况:pybrain中的activateOnDataset
将为您提供两个类别的概率(在上面的示例中,我们只取概率的最大值来确定考虑哪个类)。然后,只需将其转换为PyROC期望的格式,就像random_mixture_model
一样,它应该会为您提供ROC曲线。