- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我需要在 sklearn 中使用自定义分数执行单变量特征选择,因此我使用的是 GenericUnivariateSelect。但是,正如在文档中一样,
选择器的模式:{‘percentile’, ‘k_best’, ‘fpr’, ‘fdr’, ‘fwe’}
在我的例子中,我需要选择分数高于某个值的特征,所以我实现了:
from sklearn.feature_selection.univariate_selection import _clean_nans
from sklearn.feature_selection.univariate_selection import f_classif
import numpy as np
import pandas as pd
from sklearn.feature_selection import GenericUnivariateSelect
from sklearn.metrics import make_scorer
from sklearn.feature_selection.univariate_selection import _BaseFilter
from sklearn.pipeline import Pipeline
class SelectMinScore(_BaseFilter):
# Sklearn documentation: modes for selectors : {‘percentile’, ‘k_best’, ‘fpr’, ‘fdr’, ‘fwe’}
# custom selector:
# select features according to the k highest scores.
def __init__(self, score_func=f_classif, minScore=0.7):
super(SelectMinScore, self).__init__(score_func)
self.minScore = minScore
self.score_func=score_func
[...]
def _get_support_mask(self):
check_is_fitted(self, 'scores_')
if self.minScore == 'all':
return np.ones(self.scores_.shape, dtype=bool)
else:
scores = _clean_nans(self.scores_)
mask = np.zeros(scores.shape, dtype=bool)
# Custom part
# only score above the min
mask=scores>self.minScore
if not np.any(mask):
mask[np.argmax(scores)]=True
return mask
但是,我还需要使用自定义评分函数,它必须在此处接收额外的参数 (XX
):不幸的是,我无法使用 make_scorer
def Custom_Score(X,Y,XX):
return 1
class myclass():
def mymethod(self,_XX):
custom_filter=GenericUnivariateSelect(Custom_Score(XX=_XX),mode='MinScore',param=0.7)
custom_filter._selection_modes.update({'MinScore': SelectMinScore})
MyProcessingPipeline=Pipeline(steps=[('filter_step', custom_filter)])
# finally
X=pd.DataFrame(data=np.random.rand(500,3))
y=pd.DataFrame(data=np.random.rand(500,1))
MyProcessingPipeline.fit(X,y)
MyProcessingPipeline.transform(X,y)
_XX=np.random.rand(500,1
C=myclass()
C.mymethod(_XX)
这会引发以下错误:
Traceback (most recent call last):
File "<ipython-input-37-f493745d7e1b>", line 1, in <module>
runfile('C:/Users/_____/Desktop/pd-sk-integration.py', wdir='C:/Users/_____/Desktop')
File "C:\Users\______\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Users\\______\\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)=
File "C:/Users/______/Desktop/pd-sk-integration.py", line 65, in <module>
C.mymethod()
File "C:/Users/______/Desktop/pd-sk-integration.py", line 55, in mymethod
custom_filter=GenericUnivariateSelect(Custom_Score(XX=_XX),mode='MinScore',param=0.7)
TypeError: Custom_Score() takes exactly 3 arguments (1 given)
我尝试通过向我的 SelectMinScore
函数的 fit()
添加额外的 kwarg (XX)
并通过传递它作为一个合适的参数。正如@TomDLT 所建议的那样,
custom_filter = SelectMinScore(minScore=0.7)
pipe = Pipeline(steps=[('filter_step', custom_filter)])
pipe.fit(X,y, filter_step__XX=XX)
但是,如果我这样做
line 291, in set_params
(key, self.__class__.__name__))
ValueError: Invalid parameter XX for estimator SelectMinScore. Check the list of available parameters with `estimator.get_params().keys()`.
最佳答案
正如您在 the code 中看到的那样, scorer 函数不会用额外的参数调用,所以目前在 scikit-learn 中没有简单的方法来传递你的样本属性 XX
。
对于您的问题,一个稍微老套的方法可能是更改 SelectMinScore
中的函数 fit
,添加一个额外的参数 XX
:
def fit(self, X, y, XX):
"""..."""
X, y = check_X_y(X, y, ['csr', 'csc'], multi_output=True)
if not callable(self.score_func):
raise TypeError("The score function should be a callable, %s (%s) "
"was passed."
% (self.score_func, type(self.score_func)))
self._check_params(X, y)
score_func_ret = self.score_func(X, y, XX)
if isinstance(score_func_ret, (list, tuple)):
self.scores_, self.pvalues_ = score_func_ret
self.pvalues_ = np.asarray(self.pvalues_)
else:
self.scores_ = score_func_ret
self.pvalues_ = None
self.scores_ = np.asarray(self.scores_)
return self
然后您可以使用 extra fit params 调用管道:
custom_filter = SelectMinScore(minScore=0.7)
pipe = Pipeline(steps=[('filter_step', custom_filter)])
pipe.fit(X,y, filter_step__XX=XX)
关于python - 将额外参数传递给 sklearn 管道中的自定义评分函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46606855/
当我搜索“iphone”时,我有以下记录和分数 - 记录1: 字段名称 - 显示名称:“iPhone” 字段名称 - 名称:“iPhone” 11.654595 = (MATCH) sum of:
Types Description: parent type 1)Parent Type: "product" 2)childType : "ratings" 问题描述:我有一个es查询(q
如果您使用 Freebase 搜索按名称获取任何实体的匹配项,您将获得按 relevance score 排序的结果.例如尝试 Taj Mahal . 我正在尝试使用 Freebase 数据转储获得类
我试图根据多个不同的标准给不同的城市打从 1 到 5 的“分数”,最终将分数相加并决定哪个城市最好。 表“international_tobacco_alcohol”包含居民用于酒精和烟草的收入百分比
我有一年中任何一个季度的索引(“index-2015.1”,“index-2015.2”...) 我在每个索引上有大约 3000 万个文档。 文档有一个文本字段('title') 我的文档排序方式是(
我有一个数组,我想根据为数组中的每个元素分配一个分数来排序。 假设可能的分数范围是 0-100。为了获得该分数,我们将使用 2 个比较数据点,一个权重为 75,一个权重为 25。我们称它们为 valu
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 4 年前。 Improve this qu
做一排星星作为评级是微不足道的,但我不确定做随机数的正确 flutter 方法是什么? 换句话说,假设我的评分最多为 5 颗星,我该怎么做,只有一颗或两颗星?我可以有一个 switch 语句,并返回带
我需要创建一个灵活的(最好是动态的)评分引擎,就像信用评分或保费计算系统一样。有创建评分引擎实践经验的人有任何建议、示例或建议模式吗? 我已经知道: Rete Algorithm FICO The o
我的索引中有以下类型的文档,但由于深度嵌套方面,找不到正确排序的方法。 文档示例: { "metadatas": [{ "name": "name", "timeValidity"
我正在寻找 Lucene (Java) 中的相似性模块,它给出基于权重的分数。我知道这很模糊,最好用一个例子来解释。 Document 1 ----------- Firstname: Frances
我对 Lucene 8 比较陌生,想了解如何将旧版 Solr 4 评分迁移到 Lucene。这就是 Solr 4 目前的做法。 /* * From the SolrRelevan
我正在使用 Lucene 来构建标记共现的大型索引(例如 [elephant,animal]、[melon,fruit]、[宝马,汽车],...)。我使用 BooleanQuery 查询索引以获取绝对
Ratingbar 星未正确显示。我不知道我做错了什么。当我使用自定义样式时,只显示一颗星,它的长度等于 5 星。 风格是: @drawable/manual_ratingbar
我编写了一个程序,它读取 imdb 上排名前 250 的电影的名称和评分,并返回评分的平均值。我有以下程序 import java.io.IOException; import org.jsoup.*
我有一个直截了当的问题,我将 ngram 用于部分匹配。实现效果很好,但得分结果并不像我希望的那样有效。我希望我的分数结果看起来像这样: 柯:.1 Kev:.2 凯维:.3 凯文:.4 相反,我得到以
假设我有一个像这样的 MySQL 表: 软件表: id int name text votes int rating int 其中投票是某人为该项目投票的次数,评分是这些投票的平均值。 示例数据: i
我在索引期间使用过滤器 EdgeNGramTokenFilter。 当我寻找一个词时。当 Lucene 找到完整单词或另一个单词的一部分时,它的评分不会产生差异。 例如,如果我正在查找单词 PUB。我
我们正在使用 java 并使用 elasticsearch java api 开发一个应用程序。我们对元数据建立了索引,并希望在索引时或搜索时使用排名/评分。 而且,我不知道是否可以对用户单击结果时选
有人可以解释(或引用引用资料)用更简单的词来比较 SOLR 和 LUCENE 使用的评分机制。 它们有什么区别吗? 我不太擅长 solr/lucene,但我的发现表明它们似乎不同。 P.S:我只是尝试
我是一名优秀的程序员,十分优秀!