構建我的第乙個機器學習 岩石水雷聲吶分類器

2021-08-08 07:44:46 字數 4397 閱讀 9744

終於要構建機器學習分類器啦,激動,學玩這個才發現,python實在是會讓人變懶的,構建分類器竟然不用寫線性回歸學習過程…..直接用sklearn包就可以了

部分資料參考自:參考**&書

訓練測試資料:資料位址

直接貼**吧:

# -*- coding:utf-8 -*-

import urllib.request

import numpy

import random

from sklearn import datasets,linear_model

from sklearn.metrics import roc_curve,auc

import pylab as pl

defconfusionmatrix

(predicted,actual,threshold):

if len(predicted)!=len(actual):return -1

tp=0.0

fp=0.0

tn=0.0

fn=0.0

for i in range(len(actual)):

if actual[i]>0.5:

if predicted[i]>threshold:

tp+=1.0

else:

fn+=1.0

else:

if predicted[i]1.0

else:

fp+=1.0

rtn=[tp,fn,fp,tn]

return rtn

url=''

data=urllib.request.urlopen(url)

xlist=

labels=

for line in data:

row=line.strip().split(b',')

if(row[-1]==b"m"):#原書中**是row[-1] == 'm'因為我們上面修改了**,使row[-1]值變成了b'm',...,b'r',如果不加以修改,那麼下面得到的所有labels值都為零,baidu了好久才發現的

else:

row.pop()

floatrow=[float(num) for num in row]

xlisttest=[xlist[i] for i in range(len(xlist)) if i%3 == 0]

xlisttrain=[xlist[i] for i in range(len(xlist)) if i%3 != 0]

labelstest=[labels[i] for i in range(len(xlist)) if i%3 == 0]

labelstrain=[labels[i] for i in range(len(xlist)) if i%3 != 0]

xtrain=numpy.array(xlisttrain)

ytrain=numpy.array(labelstrain)

xtest=numpy.array(xlisttest)

ytest=numpy.array(labelstest)

#print(xtrain)

#print(ytrain)

print("shape of xtrain array", xtrain.shape)

print("shape of ytrain array", ytrain.shape)

print("shape of xtest array", xtest.shape)

print("shape of ytest array", ytest.shape)

rocksvminesmodel=linear_model.linearregression()

rocksvminesmodel.fit(xtrain,ytrain)

trainingpredictions=rocksvminesmodel.predict(xtrain)

#print('the trainingpredictions=', trainingpredictions)

confusionmattrain=confusionmatrix(trainingpredictions,ytrain,0.5)

tp=confusionmattrain[0]

fn=confusionmattrain[1]

fp=confusionmattrain[2]

tn=confusionmattrain[3]

print("tp = " + str(tp) + "\tfn = " + str(fn) + "\n" + "fp = " + str(fp) + "\ttn = " + str(tn) + '\n')

testpredictions=rocksvminesmodel.predict(xtest)

#print('the trainingpredictions=', trainingpredictions)

conmattest=confusionmatrix(testpredictions,ytest,0.5)

tp=conmattest[0]

fn=conmattest[1]

fp=conmattest[2]

tn=conmattest[3]

print("tp = " + str(tp) + "\tfn = " + str(fn) + "\n" + "fp = " + str(fp) + "\ttn = " + str(tn) + '\n')

#通過roc_curve()函式,求出fpr和tpr,以及閾值(fp正確率,tp正確率)

fpr,tpr,thresholds=roc_curve(ytrain,trainingpredictions)

roc_auc = auc(fpr, tpr)

print('auc for in-sample roc curve: '+str(roc_auc))

pl.clf()

pl.plot(fpr, tpr, label='roc curve (area = %0.2f)' % roc_auc)

pl.plot([0, 1], [0, 1], 'k-')

pl.xlim([0.0, 1.0])

pl.ylim([0.0, 1.0])

pl.xlabel('false positive rate')

pl.ylabel('true positive rate')

pl.title('in sample roc rocks versus mines')

pl.legend(loc="lower right")

pl.show()

fpr,tpr,thresholds=roc_curve(ytest,testpredictions)

roc_auc = auc(fpr, tpr)

print('auc for out-sample roc curve: '+str(roc_auc))

pl.clf()

pl.plot(fpr, tpr, label='roc curve (area = %0.2f)' % roc_auc)

pl.plot([0, 1], [0, 1], 'k-')

pl.xlim([0.0, 1.0])

pl.ylim([0.0, 1.0])

pl.xlabel('false positive rate')

pl.ylabel('true positive rate')

pl.title('in sample roc rocks versus mines')

pl.legend(loc="lower right")

pl.show()

測試結果:

可以看到訓練結果還是不錯的

機器學習第乙個演算法

單變數線性回歸 導包import numpy as np import matplotlib.pyplot as plt plt.rcparams font.sans serif simhei 正常顯示中文 plt.rcparams axes.unicode minus false 正常顯示符號 讀...

Python機器學習 第乙個機器學習專案

資料集 1.導入庫 import pandas as pd import numpy as np import matplotlib as plt from sklearn.model selection import train test split from sklearn.model sele...

第一章 乙個極小的機器學習應用 構建第乙個模型

誤差計算 使用 值到真實值距離的平方來計算誤差 def error f,x,y return sp.sum f x y 2 從一條簡單的直線開始 scipy中的polyfit 多項式擬合 函式使用者解決這個問題。給定資料x和y,以及期望的多項式的階 直線的階是1 可以找到乙個模型,能夠最小化之前定義...