Python 获得;缺少2个必需的位置参数“;由于我传给cross_val_score的自定义记分员

Python 获得;缺少2个必需的位置参数“;由于我传给cross_val_score的自定义记分员,python,pandas,scikit-learn,Python,Pandas,Scikit Learn,因此,主要的想法是创建一个定制的记分器,以测量特异性,因为它不是scikit learn预先定义的评分方法的一部分 该方法似乎工作正常,但是,当我尝试将cross_val_分数的结果传递到稍后使用seaborn boxplot绘制的数据帧时,我得到以下错误 TypeError:\uuuu call\uuuu()缺少两个必需的位置参数:“X”和“y\u true” 调用cross_val_分数的过程 mbox = pd.DataFrame() for metric

因此,主要的想法是创建一个定制的记分器,以测量特异性,因为它不是scikit learn预先定义的评分方法的一部分

该方法似乎工作正常,但是,当我尝试将cross_val_分数的结果传递到稍后使用seaborn boxplot绘制的数据帧时,我得到以下错误

TypeError:\uuuu call\uuuu()缺少两个必需的位置参数:“X”和“y\u true”

调用cross_val_分数的过程

        mbox = pd.DataFrame()
        for metric in metrics:
            if metric == 'specificity':
                metric = make_scorer(custom_specificity)
            results = cross_val_score(model, x_test_m, y_test_m, cv=cv_num, scoring=metric)
            print('results', type(results))
            if show_raw_data:
                raw = np.array2string(results, threshold=np.inf, max_line_width=np.inf, separator=',')
                raw.replace('\n', '').replace(' ', '')
                print(metric, ": %.3f%% Std.: %.3f%%" % (results.mean() * 100.0, results.std() * 100.0))
                print("Metric raw data: ", raw)
            mbox[metric] = results
对于其余的预判得分手,我得到以下结果

results <class 'numpy.ndarray'>
accuracy : 87.361% Std.: 4.934%
Metric raw data:  [0.8125    ,0.875     ,0.93333333]
results <class 'numpy.ndarray'>
make_scorer(custom_specificity) : 83.333% Std.: 11.785%
Metric raw data:  [0.75,0.75,1.  ]
自定义度量函数

def custom_measure(y_actual, y_hat):
    tp, fp, tn, fn = 0, 0, 0, 0
    cm = confusion_matrix(y_actual, y_hat)
    tn = cm[0][0]
    fn = cm[1][0]
    tp = cm[1][1]
    fp = cm[0][1]
    return tp, fp, tn, fn
堆栈跟踪

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-0ebc81311532> in <module>
      2 trained_models_using_pca_comp = train.train_models(pca_train_x, pca_train_y, pca_test_x, pca_test_y)
      3 evaluate.generate_metrics(trained_models_using_pca_comp, pca_test_x, pca_test_y, 
----> 4                           ['accuracy', 'precision', 'recall', 'f1', 'specificity'], cv_num=cross_val_num, show_raw_data=True)

~\thesisProject\thesis\moduleMetrics.py in generate_metrics(models, x_test, y_test, metrics, cv_num, show_raw_data)
     74                     print(metric, ": %.3f%% Std.: %.3f%%" % (results.mean() * 100.0, results.std() * 100.0))
     75                     print("Metric raw data: ", raw)
---> 76                 mbox[metric] = results
     77 
     78             # plot confusion matrix

~\anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3023 
   3024     def __setitem__(self, key, value):
-> 3025         key = com.apply_if_callable(key, self)
   3026 
   3027         # see if we can slice the rows

~\anaconda3\lib\site-packages\pandas\core\common.py in apply_if_callable(maybe_callable, obj, **kwargs)
    339     """
    340     if callable(maybe_callable):
--> 341         return maybe_callable(obj, **kwargs)
    342 
    343     return maybe_callable

TypeError: __call__() missing 2 required positional arguments: 'X' and 'y_true'
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
2个使用pca\U comp=训练的训练模型(pca\U训练模型、pca\U训练模型、pca\U测试模型、pca\U测试模型)
3.评估、生成度量(使用pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca、pca,
---->4[‘准确度’、‘精密度’、‘召回率’、‘f1’、‘特异性’],变异数=交叉值,显示原始数据=真)
生成度量(模型、x检验、y检验、度量、cv数值、显示原始数据)中的~\theisproject\thesis\moduleMetrics.py
74打印(公制,“:%.3f%%标准:%.3f%%”百分比)(results.mean()*100.0,results.Std()*100.0))
75打印(“公制原始数据:”,原始)
--->76 mbox[度量]=结果
77
78#绘制混淆矩阵
~\anaconda3\lib\site packages\pandas\core\frame.py in\uuuuuu setitem\uuuuuuuu(self、key、value)
3023
3024定义设置项(自身、键、值):
->3025 key=com.apply\u如果可调用(key,self)
3026
3027#看看我们能不能把这些行切掉
~\anaconda3\lib\site packages\pandas\core\common.py中的apply\u if\u可调用(可能可调用,obj,**kwargs)
339     """
340如果可调用(可能可调用):
-->341返回可调用(obj,**kwargs)
342
343返回可能是可调用的
TypeError:\uuuu调用\uuuu()缺少2个必需的位置参数:“X”和“y\u true”

好的,多亏了@David M。我意识到我刚刚通过了一个
作为数据帧的键

因此,我解决这个问题的方法是首先检查该点的度量类型,使用

isinstance(type(metric),str)
如果它是一个_PredictScorer,我只需传递一个自定义记分器的名称作为数据帧的键。

对我来说效果很好,因此它必须取决于您的数据集。顺便说一句,当您设置
mbox[metric]=results
并且度量是
scorer\u specification
,您将
mbox
字典的
make\u scorer(自定义\u specification,越大越好=False)
,而不是字符串
'scorer\u specification'
(我猜这不是您想要的).我想你是对的,我刚才在我的代码的另一部分也看到了类似的东西。谢谢你提及。大卫·M.解决了你的问题吗?@gtomer是的,他解决了,我在解释他的评论时确实犯了一个错误。
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-0ebc81311532> in <module>
      2 trained_models_using_pca_comp = train.train_models(pca_train_x, pca_train_y, pca_test_x, pca_test_y)
      3 evaluate.generate_metrics(trained_models_using_pca_comp, pca_test_x, pca_test_y, 
----> 4                           ['accuracy', 'precision', 'recall', 'f1', 'specificity'], cv_num=cross_val_num, show_raw_data=True)

~\thesisProject\thesis\moduleMetrics.py in generate_metrics(models, x_test, y_test, metrics, cv_num, show_raw_data)
     74                     print(metric, ": %.3f%% Std.: %.3f%%" % (results.mean() * 100.0, results.std() * 100.0))
     75                     print("Metric raw data: ", raw)
---> 76                 mbox[metric] = results
     77 
     78             # plot confusion matrix

~\anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3023 
   3024     def __setitem__(self, key, value):
-> 3025         key = com.apply_if_callable(key, self)
   3026 
   3027         # see if we can slice the rows

~\anaconda3\lib\site-packages\pandas\core\common.py in apply_if_callable(maybe_callable, obj, **kwargs)
    339     """
    340     if callable(maybe_callable):
--> 341         return maybe_callable(obj, **kwargs)
    342 
    343     return maybe_callable

TypeError: __call__() missing 2 required positional arguments: 'X' and 'y_true'