这样找到的。也许代码不是最优的,对此感到抱歉。
好的,让我们开始吧:
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.metrics.scorer import make_scorer
xTrain = np.random.rand(100, 100)
yTrain = np.random.randint(1, 4, (100, 1))
yTrainCV = np.random.randint(1, 4, (100, 1))
model = LogisticRegression()
yTrainCV 将在此处用作自定义记分器。
def customLoss(xArray, yArray):
indices = xArray.index.values
tempArray = [1 if value1 != value2 else 0 for value1, value2 in zip(xArray.values, yTrainCV[[indices]])]
return sum(tempArray)
scorer = {'main': 'accuracy',
'custom': make_scorer(customLoss, greater_is_better=True)}
这里有一些技巧:
- 您需要将值传递给 customLoss 2(来自模型的预测值 + 实际值;但我们不使用第二个参数)
-
greater_is_better 有一些游戏:True/False 将返回正数或负数
- 我们从
GridSearchCV 中的 CV 获得的指数
还有……
grid = GridSearchCV(model,
scoring=scorer,
cv=5,
param_grid={'C': [1e0, 1e1, 1e2, 1e3],
'class_weight': ['balanced', None]},
refit='custom')
grid.fit(xTrain, pd.DataFrame(yTrain))
print(grid.score(xTrain, pd.DataFrame(yTrain)))
- 不要忘记
GridSearchCV中的refit参数
- 我们在这里将目标数组作为
DataFrame 传递 - 这将帮助我们检测自定义损失函数中的索引