- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我继续调查管道。我的目标是仅使用管道执行机器学习的每个步骤。将我的管道与其他用例相适应会更加灵活和容易。所以我做什么:
这是我的代码:
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_selection import SelectKBest
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
class FillNa(BaseEstimator, TransformerMixin):
def transform(self, x, y=None):
non_numerics_columns = x.columns.difference(
x._get_numeric_data().columns)
for column in x.columns:
if column in non_numerics_columns:
x.loc[:, column] = x.loc[:, column].fillna(
df[column].value_counts().idxmax())
else:
x.loc[:, column] = x.loc[:, column].fillna(
x.loc[:, column].mean())
return x
def fit(self, x, y=None):
return self
class CategoricalToNumerical(BaseEstimator, TransformerMixin):
def transform(self, x, y=None):
non_numerics_columns = x.columns.difference(
x._get_numeric_data().columns)
le = LabelEncoder()
for column in non_numerics_columns:
x.loc[:, column] = x.loc[:, column].fillna(
x.loc[:, column].value_counts().idxmax())
le.fit(x.loc[:, column])
x.loc[:, column] = le.transform(x.loc[:, column]).astype(int)
return x
def fit(self, x, y=None):
return self
class Perf(BaseEstimator, TransformerMixin):
def fit(self, clf, x, y, perf="all"):
"""Only for classifier model.
Return AUC, ROC, Confusion Matrix and F1 score from a classifier and df
You can put a list of eval instead a string for eval paramater.
Example: eval=['all', 'auc', 'roc', 'cm', 'f1'] will return these 4
evals.
"""
evals = {}
y_pred_proba = clf.predict_proba(x)[:, 1]
y_pred = clf.predict(x)
perf_list = perf.split(',')
if ("all" or "roc") in perf.split(','):
fpr, tpr, _ = roc_curve(y, y_pred_proba)
roc_auc = round(auc(fpr, tpr), 3)
plt.style.use('bmh')
plt.figure(figsize=(12, 9))
plt.title('ROC Curve')
plt.plot(fpr, tpr, 'b',
label='AUC = {}'.format(roc_auc))
plt.legend(loc='lower right', borderpad=1, labelspacing=1,
prop={"size": 12}, facecolor='white')
plt.plot([0, 1], [0, 1], 'r--')
plt.xlim([-0.1, 1.])
plt.ylim([-0.1, 1.])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
if "all" in perf_list or "auc" in perf_list:
fpr, tpr, _ = roc_curve(y, y_pred_proba)
evals['auc'] = auc(fpr, tpr)
if "all" in perf_list or "cm" in perf_list:
evals['cm'] = confusion_matrix(y, y_pred)
if "all" in perf_list or "f1" in perf_list:
evals['f1'] = f1_score(y, y_pred)
return evals
path = '~/proj/akd-doc/notebooks/data/'
df = pd.read_csv(path + 'titanic_tuto.csv', sep=';')
y = df.pop('Survival-Status').replace(to_replace=['dead', 'alive'],
value=[0., 1.])
X = df.copy()
X_train, X_test, y_train, y_test = train_test_split(
X.copy(), y.copy(), test_size=0.2, random_state=42)
percent = 0.50
nb_features = round(percent * df.shape[1]) + 1
clf = RandomForestClassifier()
pipeline = Pipeline([('fillna', FillNa()),
('categorical_to_numerical', CategoricalToNumerical()),
('features_selection', SelectKBest(k=nb_features)),
('random_forest', clf),
('perf', Perf())])
params = dict(random_forest__max_depth=list(range(8, 12)),
random_forest__n_estimators=list(range(30, 110, 10)))
cv = GridSearchCV(pipeline, param_grid=params)
cv.fit(X_train, y_train)
我知道打印 roc 曲线并不理想,但现在这不是问题。
所以,当我执行这段代码时,我有:
TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator Pipeline(steps=[('fillna', FillNa()), ('categorical_to_numerical', CategoricalToNumerical()), ('features_selection', SelectKBest(k=10, score_func=<function f_classif at 0x7f4ed4c3eae8>)), ('random_forest', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None,...=1, oob_score=False, random_state=None,
verbose=0, warm_start=False)), ('perf', Perf())]) does not.
我对所有的想法都感兴趣......
最佳答案
如错误所述,您需要在 GridSearchCV 中指定评分参数。
使用
GridSearchCV(pipeline, param_grid=params, scoring = 'accuracy')
编辑(根据评论中的问题):
如果您需要整个 X_train 和 y_train(而不是 GridSearchCV 的所有拆分)的 roc、auc 曲线和 f1,最好将 Perf 类排除在管道之外。
pipeline = Pipeline([('fillna', FillNa()),
('categorical_to_numerical', CategoricalToNumerical()),
('features_selection', SelectKBest(k=nb_features)),
('random_forest', clf)])
#Fit the data in the pipeline
pipeline.fit(X_train, y_train)
performance_meas = Perf()
performance_meas.fit(pipeline, X_train, y_train)
关于python - 在管道中的分类器之后使用度量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43787107/
背景信息:对于国际销售表中的每一行,我需要检索过去特定日期的美元汇率,以便分析人员确定汇率变化的影响关于销售数字。然后,我将使用今天的汇率与过去的汇率之间的差值,并将其乘以销售额来确定影响。 实际问题
是否可以通过切片器值动态选取表中定义的适当 DAX 度量? 源表: +----------------+------------+ | col1 | col2 | +-
我有一个 ViewFlipper在我的主要 Activity View 上。在 onCreate 我实例化添加到 ViewFlipper 的 View 。之后,我将显示的 child 设置为第一个。当
我正在研究句子类别检测问题。每个句子可以属于多个类别例如: "It has great sushi and even better service." True Label: [[ 0. 0.
谁能帮我一起计算F-measure?我知道如何计算召回率和准确率,但不知道对于给定的算法如何计算一个 F-measure 值。 例如,假设我的算法创建了 m 个集群,但我知道相同数据有 n 个集群(由
我对通过宏精度和手动召回计算宏 f1-score 感兴趣。但结果并不相等。代码中 f1 和 f1_new 的最终公式有什么区别? from sklearn.metrics import precisi
我有一张记录了一些人体重的表格: Year Person Weight 2010 Mike 75 2010 Laura 60 2011 Mike 80 201
df分为训练数据帧和测试数据帧。训练数据帧分为训练数据帧和测试数据帧。因变量Y是二进制(因子),值为 0 和 1。我试图用此代码(神经网络,插入符号包)预测概率: library(caret) mod
我想使用 Hausdorff 距离作为训练指标,但我刚刚找到了 Weighted_Hausdorff_loss并将其用作医学图像分割的指标。 import math import numpy as n
我有一段时间没有使用 R,所以也许我只是不习惯它,但是..我在 R 中有一个表,有两个列,第一个有预测值(值可以是 0 或 1 ),第二个具有实际值(也是 0 或 1)。我需要找到召回率、精度和 f
我正在使用 Collectd 收集系统指标。我正在小范围内收集测量值以获得准确的值。但是我想使用 Statsd 在本地聚合这些值。 Statsd 应该聚合这些值并以更长的时间间隔将它们发送到 libr
我使用SciKit作为一个库来处理分类算法,例如:NB、SVM。 这是一个非常漂亮的binary classification implementation对于“垃圾邮件和HAM”电子邮件:
我正在寻找 MST 启发式算法的严格示例,它是度量旅行商问题的 2 近似算法。 这个算法在网上很容易找到,但我找不到具体的例子。我所说的严格示例是指给定算法返回的解决方案比最佳解决方案差 2 倍的示例
我使用 Data Studio 中的 Case 函数来确定某个值是否高于或低于 6,000 英镑,并根据输出呈现两个数字之一。这两个数字是计算字段。 第一个案例陈述: (大于或小于)- CASE WH
我正在使用 Ganglia + RRDTool为 monitoring a web farm .很多图很清楚,但是当我看到load_one metric , 我 don't have Y-axis l
以下是股票交易数据的简化版本。 StockData = DATATABLE ( "STOCK", STRING, "Date", DATETIME, "Buyer", STRI
我正在尝试将ASP.NET Core 7应用程序中的度量/跟踪发送到Grafana。。这是我的《码头工人》作文文件。。下面是我的收集器配置:。下面是配置OpenTelemeter的服务集合扩展方法。。
我正试图从我的ASP.NET Core 7应用程序向Grafana发送度量/跟踪。。这是我的《码头工人》作文文件。。下面是我的收集器配置:。下面是配置OpenTelemeter的服务集合扩展方法。。首
我是一名优秀的程序员,十分优秀!