sklearn BaseEstimator

来源:互联网 发布:win7设置网络连接 编辑:程序博客网 时间:2024/05/22 09:45

http://www.cnblogs.com/foreveryl/p/3616506.html 

看了一个python项目开源源码, 才知道现在这点python知识实在是弱爆了..  

尼玛就像学了2500个常用汉字, 然后要去理解"楚辞"..

 

代码如下, 解释一点一点从网上查, 随后:

复制代码
  1 ###############################################################################  2 class BaseEstimator(object):  3     """Base class for all estimators in scikit-learn  4   5     Notes  6     -----  7     All estimators should specify all the parameters that can be set  8     at the class level in their __init__ as explicit keyword  9     arguments (no *args, **kwargs). 10     """ 11  12     @classmethod 13     def _get_param_names(cls): 14         """Get parameter names for the estimator""" 15         try: 16             # fetch the constructor or the original constructor before 17             # deprecation wrapping if any 18             init = getattr(cls.__init__, 'deprecated_original', cls.__init__) 19  20             # introspect the constructor arguments to find the model parameters 21             # to represent 22             args, varargs, kw, default = inspect.getargspec(init) 23             if not varargs is None: 24                 raise RuntimeError("scikit-learn estimators should always " 25                                    "specify their parameters in the signature" 26                                    " of their __init__ (no varargs)." 27                                    " %s doesn't follow this convention." 28                                    % (cls, )) 29             # Remove 'self' 30             # XXX: This is going to fail if the init is a staticmethod, but 31             # who would do this? 32             args.pop(0) 33         except TypeError: 34             # No explicit __init__ 35             args = [] 36         args.sort() 37         return args 38  39     def get_params(self, deep=True): 40         """Get parameters for this estimator. 41  42         Parameters 43         ---------- 44         deep: boolean, optional 45             If True, will return the parameters for this estimator and 46             contained subobjects that are estimators. 47  48         Returns 49         ------- 50         params : mapping of string to any 51             Parameter names mapped to their values. 52         """ 53         out = dict() 54         for key in self._get_param_names(): 55             # We need deprecation warnings to always be on in order to 56             # catch deprecated param values. 57             # This is set in utils/__init__.py but it gets overwritten 58             # when running under python3 somehow. 59             warnings.simplefilter("always", DeprecationWarning) 60             try: 61                 with warnings.catch_warnings(record=True) as w: 62                     value = getattr(self, key, None) 63                 if len(w) and w[0].category == DeprecationWarning: 64                 # if the parameter is deprecated, don't show it 65                     continue 66             finally: 67                 warnings.filters.pop(0) 68  69             # XXX: should we rather test if instance of estimator? 70             if deep and hasattr(value, 'get_params'): 71                 deep_items = value.get_params().items() 72                 out.update((key + '__' + k, val) for k, val in deep_items) 73             out[key] = value 74         return out 75  76     def set_params(self, **params): 77         """Set the parameters of this estimator. 78  79         The method works on simple estimators as well as on nested objects 80         (such as pipelines). The former have parameters of the form 81         ``<component>__<parameter>`` so that it's possible to update each 82         component of a nested object. 83  84         Returns 85         ------- 86         self 87         """ 88         if not params: 89             # Simple optimisation to gain speed (inspect is slow) 90             return self 91         valid_params = self.get_params(deep=True) 92         for key, value in six.iteritems(params): 93             split = key.split('__', 1) 94             if len(split) > 1: 95                 # nested objects case 96                 name, sub_name = split 97                 if not name in valid_params: 98                     raise ValueError('Invalid parameter %s for estimator %s' % 99                                      (name, self))100                 sub_object = valid_params[name]101                 sub_object.set_params(**{sub_name: value})102             else:103                 # simple objects case104                 if not key in valid_params:105                     raise ValueError('Invalid parameter %s ' 'for estimator %s'106                                      % (key, self.__class__.__name__))107                 setattr(self, key, value)108         return self109 110     def __repr__(self):111         class_name = self.__class__.__name__112         return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),113                                                offset=len(class_name),),)114 115     def __str__(self):116         class_name = self.__class__.__name__117         return '%s(%s)' % (class_name,118                            _pprint(self.get_params(deep=True),119                                    offset=len(class_name), printer=str,),)
复制代码

 

 

1, @classmethod

http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html 

classmethod:类方法
staticmethod:静态方法

在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:

    • @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。 
    • 普通对象方法至少需要一个self参数,代表类对象实例
    • 类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。 
    • 静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少

 

2, getarrt() 函数

详解: http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html

简单的说:

这个函数的作用相当于是  object.name.  只不过这里可以把name作为一个变量去处理. 

这就有很大的方便.  以前要传回调函数, 需要传个(函数) 对象, 现在穿个string 就可以了. 

string么, 随意多了.. 不用先定义好. 

例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

import statsout 

def output(data, format="text"):                           
    output_function = getattr(statsout, "output_%s" %format
    return output_function(data)
 
 
3, inspect 模块:

详解: http://my.oschina.net/taisha/blog/55597 

简单来说: inspect 模块是可以提供python 反射机制:

(1).对是否是模块,框架,函数等进行类型检查。

(2).获取源码

(3).获取类或函数的参数的信息

(4).解析堆栈

getargspec(func): 
仅用于方法,获取方法声明的参数,返回元组,分别是(普通参数名的列表, *参数名, **参数名, 默认值元组)。如果没有值,将是空列表和3个None。如果是2.6以上版本,将返回一个命名元组(Named Tuple),即除了索引外还可以使用属性名访问元组中的元素。

 

好了_get_param_names 这个函数意思是:  拿到这个类的构造函数的参数.

 

4, 关于函数参数:

http://blog.csdn.net/qinyilang/article/details/5484415

在python里, 定义一个函数, 可以有以下4类参数:

1)必须的参数
2)可选的参数
3)过量的位置参数
4)过量的关键字参数

1),2), 经常用, 3), 4) 是啥啊, 经常看人这么写 def func(*args, *kwargs)

这里 *args 就是3),  相当于C 里的变长参数列表.. 

**kwargs 是4), 叫" 关键词参数"..  比如: def accept(**kwargs):

kwargs 是一个字典, 里面有想用到的任何变量名. ..

可以这么调用: accept(foo='bar', spam='eggs')

 

0 0
原创粉丝点击