반응형
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

bro's coding

sklearn.base.BaseEstimator, ClassifierMixin(분류기 만들기) 본문

[AI]/python.sklearn

sklearn.base.BaseEstimator, ClassifierMixin(분류기 만들기)

givemebro 2020. 4. 27. 11:11
반응형
from sklearn.base import BaseEstimator, ClassifierMixin

class Myclassifier(BaseEstimator,ClassifierMixin):
    def __init__(self):
        # __init__ 메소드에 필요한 모든 매개변수를 나열함
        result=0
        
        
    def fit(self,X,y):
        # fit 메소드는 X와 y매개변수만을 갖음
        # 모델 학습
        return self
        
    
    def predict(self,X):
        # X만 받음
        pred_y=np.zeros(len(X))+self.result
        return pred_y

 

 

 

 


score 등을 만들지 않아도 사용 할 수 있다.

 

from sklearn.base import BaseEstimator, TransformerMixin ,ClassifierMixin
import numpy as np
class MYClass(BaseEstimator,ClassifierMixin):
    def __init__(self):
        self.result=0
        self.n_class=0
        self.centers=[]
        
    def fit(self,X,y):
        self.n_class=y.max()
        for i in range(self.n_class):
            x=X[y==i]
            self.centers.append(x.mean(axis=0))
            
        return self
    def predict(self,X):
        pred_y=[]
        for x in X:
            i=[((x-c)**2).sum()for c in self.centers]
            pred_y.append(np.argmin(i))
            
        return np.array(pred_y)
        

 

 

from sklearn.datasets import load_iris
iris=load_iris()
X=iris.data
y=iris.target
model=MYClass()
model.fit(X,y)
model.predict(X)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int64)

 

 

model.score(X,y)
0.6666666666666666

 

 

model.centers
array([5.006, 3.418, 1.464, 0.244]), array([5.936, 2.77 , 4.26 , 1.326])]

 

반응형
Comments