Scikit-Learn
要运行 scikit-learn 示例,请确保已安装以下库
pip install -U scikit-learn
evaluate
中的指标可以轻松地与 Scikit-Learn 估计器或 管道 集成。
但是,这些指标要求我们生成模型的预测结果。可以将估计器中的预测结果和标签传递给 evaluate
指标以计算所需的值。
import numpy as np
np.random.seed(0)
import evaluate
from sklearn.compose import ColumnTransformer
from sklearn.datasets import fetch_openml
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
从 https://www.openml.org/d/40945 加载数据
X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True)
或者,可以从 frame 属性直接获取 X 和 y
X = titanic.frame.drop('survived', axis=1)
y = titanic.frame['survived']
我们为数值数据和分类数据创建预处理管道。请注意,pclass 可以被视为分类特征或数值特征。
numeric_features = ["age", "fare"]
numeric_transformer = Pipeline(
steps=[("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())]
)
categorical_features = ["embarked", "sex", "pclass"]
categorical_transformer = OneHotEncoder(handle_unknown="ignore")
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
将分类器附加到预处理管道。现在我们拥有完整的预测管道。
clf = Pipeline(
steps=[("preprocessor", preprocessor), ("classifier", LogisticRegression())]
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
由于 Evaluate
指标使用列表作为参考和预测结果的输入,因此我们需要将它们转换为 Python 列表。
# Evaluate metrics accept lists as inputs for values of references and predictions
y_test = y_test.tolist()
y_pred = y_pred.tolist()
# Accuracy
accuracy_metric = evaluate.load("accuracy")
accuracy = accuracy_metric.compute(references=y_test, predictions=y_pred)
print("Accuracy:", accuracy)
# Accuracy: 0.79
只要与任务和预测结果兼容,就可以将任何合适的 evaluate
指标与估计器一起使用。