随机森林算法构建岩石水雷分类器

第一个机器学习算法用了线性回归方法构建了岩石水雷分类器:构建我的第一个机器学习—-岩石水雷声呐分类器
当时学习在测试样本中的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]]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值