python物件導向程式設計

2021-08-18 14:36:40 字數 1606 閱讀 1330

用物件導向的方法進行資料的處理

昨天學習了物件導向的基礎,嘗試去用該思想去預處理機器學習的資料。基本思路是往函式中輸入資料檔案名稱和分配的比例ratio,輸出測試集,測試標籤,訓練集,訓練標籤。

from numpy import *  

from sklearn import svm #庫不能寫在函式中。

class funsvm(): #沒引數

def __init__(self,name,ratio): #定義需要給funsvm傳入2個引數,名字和比例

self.name=name

self.ratio=ratio #定義類變數

def file2mat(self):

with open(self.name) as fr:

arrayline = fr.readlines() #讀取檔案

linenum = len(arrayline)

datamat = zeros((linenum,8))

label =

index = 0

for line in arrayline:

line = line.strip()

line = line.split(",")

datamat[index,:] = line[0:8]

index += 1

return datamat,label,linenum

def classify(self):

ratio = self.ratio

x,y,length = self.file2mat()

trainnum = int(ratio * length)

x_train = x[:trainnum]

x_test = x[trainnum:]

y_train = y[:trainnum]

y_test = y[trainnum:]

return x_train,x_test,y_train,y_test

data = funsvm("pima-indians-diabetes.txt",0.8)
array([[   6.   ,  148.   ,   72.   , ...,   33.6  ,    0.627,   50.   ],    #輸出numpy矩陣

[ 1. , 85. , 66. , ..., 26.6 , 0.351, 31. ],

[ 8. , 183. , 64. , ..., 23.3 , 0.672, 32. ],

...,

[ 3. , 174. , 58. , ..., 32.9 , 0.593, 36. ],

[ 7. , 168. , 88. , ..., 38.2 , 0.787, 40. ],

[ 6. , 105. , 80. , ..., 32.5 , 0.878, 26. ]])

python 物件導向程式設計

新式類 class mynewobjecttype bases define mynewobjecttype class class suite經典類 沒有指定乙個父類,或者子類化的基本類沒有父類,就建立了乙個經典類 class mynewobjecttype define mynewobjectt...

Python物件導向程式設計

class mynewobjecttype bases define mynewobjecttype class class suite例項化 myfirstobject mynewobjecttype class mydatawithmethod object defprintfoo self p...

python物件導向程式設計

程式設計正規化 程式設計時程式設計師用特定的語法 資料結構 演算法組成的 在計算機上執行任務的過程。實現乙個任務有不同的方式,對這些不同的程式設計方式的特點進行歸納總結得出的程式設計方式類別,即為程式設計正規化。不同的程式設計正規化本質上代表對各種型別的任務採取的不同的解決問題的思路,兩種最重要的程...