第一个机器学习算法用了线性回归方法构建了岩石水雷分类器:构建我的第一个机器学习—-岩石水雷声呐分类器
当时学习在测试样本中的auc为:0.848484848485
这次算法实现了测试样本中auc为:0.945740365112
大幅提升
# -*- coding:utf-8 -*-
import urllib.request
import numpy
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.metrics import roc_auc_score,roc_curve
import matplotlib.pyplot as plot
from math import sqrt,fabs,exp
#读取数据
url='http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data'
data=urllib.request.urlopen(url)
xlist=[]
#数据转换为列表类型
for line in data:
row=line.strip().split(b',')
xlist.append(row)
xnum=[]
labels=[]
#分类转数字,其他数值转浮点型
for row in xlist:
lastcol=row.pop()
if lastcol==b'M':
labels.append(1)
else:
labels.append(0)
attrrow=[float(elt) for elt in row]
xnum.append(attrrow)
nrows=len(xnum)
ncols=len(xnum[1])
#转为numpy矩阵
x=numpy.array(xnum)
y=numpy.array(labels)
rocksvminesnames=numpy.array(['V'+str(i) for i in range(ncols)])
xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.30,random_state=531)
auc=[]
ntreelist=range(50,2000,50)
for itrees in ntreelist:
depth=None
maxfeat=8
rocksvminesrfmodel=ensemble.RandomForestClassifier(n_estimators=itrees,max_depth=depth,max_features=maxfeat,oob_score=False,random_state=531)
rocksvminesrfmodel.fit(xtrain,ytrain)
prediction=rocksvminesrfmodel.predict_proba(xtest)
auccalc=roc_auc_score(ytest,prediction[:,1:2])
auc.append(auccalc)
print("AUC")
print(auc[-1])
plot.plot(ntreelist,auc)
plot.xlabel("number of trees")
plot.ylabel("auc")
plot.show()
整体较上一篇没什么大变化,只有一个要注意:
auccalc=roc_auc_score(ytest,prediction[:,1:2])
原型:sklearn.metrics.roc_auc_score(y_true, y_score, average=’macro’, sample_weight=None)
ytest是y_true,prediction[:,1:2]是y_score
prediction[:,1:2]是切片的意思,这里是二元切片(暂时这么叫吧,因为百度没有出现过这种),第一个选择所有的第一层列表,然后选择这个列表中的序号为1的元素,在这里就是选择第二类型的可能性(predict_proba返回的)
ceshi.py;
import numpy
a=numpy.array([[0.12,0.98],[0.81,0.29],[0.5,0.4]])
print(a[2:3,1:2])
显示:选择了第一层的序号为2的元素(列表),再选择这个列表的序号为1的元素0.4
[[ 0.4]]
numpy数组切片操作:
>>> a = np.array( [[2,3,4],[5,6,7]] )
>>> print a
[[2 3 4]
[5 6 7]]
>>> print a[1,2]
7
>>> print a[1,:]
[5 6 7]
>>> print a[1,1:2]
[6]
>>> a[1,:] = [8,9,10]
>>> print a
[[ 2 3 4]
[ 8 9 10]]