Mar*_*nen 3 python parameter-passing scikit-learn gridsearchcv
我正在尝试将参数传递给 scikit learn 中的自定义估计器,但失败了。lr
我希望在网格搜索期间更改参数。问题是lr
参数没有改变......
代码示例是从此处复制和更新的
(原始代码对我来说都不起作用)
任何GridSearchCV
使用自定义估计器并更改参数的完整工作示例将不胜感激。
我在ubuntu
18.10 使用scikit-learn
0.20.2
from sklearn.model_selection import GridSearchCV
from sklearn.base import BaseEstimator, ClassifierMixin
import numpy as np
class MyClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, lr=0.1):
# Some code
print('lr:', lr)
return self
def fit(self, X, y):
# Some code
return self
def predict(self, X):
# Some code
return X % 3
params = {
'lr': [0.1, 0.5, 0.7]
}
gs = GridSearchCV(MyClassifier(), param_grid=params, cv=4)
x = np.arange(30)
y = np.concatenate((np.zeros(10), np.ones(10), np.ones(10) * 2))
gs.fit(x, y)
Run Code Online (Sandbox Code Playgroud)
特尔维辛,马库斯
lr
由于您在构造函数内进行打印,因此您无法看到值的变化。
如果我们在函数内部打印.fit()
,我们可以看到值的变化lr
。发生这种情况是因为估计器的不同副本的创建方式不同。请参阅此处了解创建多个副本的过程。
from sklearn.model_selection import GridSearchCV
from sklearn.base import BaseEstimator, ClassifierMixin
import numpy as np
class MyClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, lr=0):
# Some code
print('lr:', lr)
self.lr = lr
def fit(self, X, y):
# Some code
print('lr:', self.lr)
return self
def predict(self, X):
# Some code
return X % 3
params = {
'lr': [0.1, 0.5, 0.7]
}
gs = GridSearchCV(MyClassifier(), param_grid=params, cv=4)
x = np.arange(30)
y = np.concatenate((np.zeros(10), np.ones(10), np.ones(10) * 2))
gs.fit(x, y)
gs.predict(x)
Run Code Online (Sandbox Code Playgroud)
输出:
lr: 0
lr: 0
lr: 0
lr: 0.1
lr: 0
lr: 0.1
lr: 0
lr: 0.1
lr: 0
lr: 0.1
lr: 0
lr: 0.5
lr: 0
lr: 0.5
lr: 0
lr: 0.5
lr: 0
lr: 0.5
lr: 0
lr: 0.7
lr: 0
lr: 0.7
lr: 0
lr: 0.7
lr: 0
lr: 0.7
lr: 0
lr: 0.1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1290 次 |
最近记录: |