Python 如何在类之间传递属性(克隆问题)
我有以下代码可以正常工作:Python 如何在类之间传递属性(克隆问题),python,oop,scikit-learn,Python,Oop,Scikit Learn,我有以下代码可以正常工作: class Classifiers(object): """Multiple classifiers""" class SVM(): """ SVM Classifier Object. This is binary classifier """ @staticmethod def classifier(X, y): from sk
class Classifiers(object):
"""Multiple classifiers"""
class SVM():
"""
SVM Classifier Object.
This is binary classifier
"""
@staticmethod
def classifier(X, y):
from sklearn import svm
classifier = svm.SVC(kernel='linear', probability=True)
return(X,y,classifier)
class FeatureSelection(object):
def select_RFECV(self, X, y, clf):
"""
Feature ranking with recursive feature elimination
and cross-validated
"""
from sklearn.feature_selection import RFECV
from sklearn.svm import SVC
estimator = SVC(kernel="linear", probability=True)
# Below retrieving Clf failed
#estimator = clf
# Code below is ok
selector = RFECV(estimator, step=1, cv=5)
selector = selector.fit(X, y)
print selector.support_
return
def main():
# call estimator
svm = Classifiers.SVM()
# Create dataset
from sklearn import datasets
X, y = datasets.make_classification(n_samples = 100, n_features =20, n_classes=2)
# Feature selection
FS = FeatureSelection()
sel = FS.select_RFECV(X,y,svm)
if __name__ == '__main__':
main()
它产生如下输出:
[False True False False False True False False False False True True
False False True False False False False True]
然而,我的问题是这个。属性在classFeatureSelection()中选择\u RFECV
,
从估计器clf
获取它的一个输入。现在,这个估计器
实际上与svm=Classifiers.svm()
相同
当我注释掉estimator=SVC(kernel=“linear”,probability=True)
并取消注释estimator=clf
。我得到了这个错误:
TypeError: Cannot clone object '<__main__.SVM instance at 0x1112f0fc8>' (type <type 'instance'>): it does not seem to be a scikit-learn estimator a it does not implement a 'get_params' methods.
TypeError:无法克隆对象“”(类型):它似乎不是scikit学习估计器a它未实现“get_params”方法。
如何在类之间正确传递属性?这里有几个问题:
第一个:
svm = Classifiers.SVM()
从您的代码判断,svm现在只是一个空实例,没有成员。就像做svm=object()
一样。由于classifier
是一个静态方法(我不会判断这个决定,只是将它作为一个输入),而且是唯一的方法,所以不需要实例化这个类。这条线是不需要的
第二个:
sel = FS.select_RFECV(X,y,svm)
此方法需要X、y和clf。它是X,y,和一个空实例。这个方法应该得到什么,这是一个猜测,是:
sel = FS.select_RFECV(*Classifiers.SVM.classifier(X,y))
这将通过分类器方法的输出(X,y,分类器)
,作为方法的输入
您收到的克隆错误与您的类无关,而是与sklearn需要一个分类器并接收其他内容这一事实有关