python - y, _ assignment 在 python/sklearn 中做什么?

标签 python scikit-learn

作为 Python 的新手,我正在尝试使用 sklearn RandomForestClassifier。 yhat 的操作指南示例如下:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75
df['species'] = pd.Factor(iris.target, iris.target_names)
df.head()

train, test = df[df['is_train']==True], df[df['is_train']==False]

features = df.columns[:4]
clf = RandomForestClassifier(n_jobs=2)
y, _ = pd.factorize(train['species']) # assignment I don't understand
clf.fit(train[features], y)

preds = iris.target_names[clf.predict(test[features])]
pd.crosstab(test['species'], preds, rownames=['actual'], colnames=['preds'])

能否解释一下 y, _ 赋值的作用及其工作原理。它没有明确使用,但如果我不使用它,我会收到错误消息。

最佳答案

您将返回的元组分解为两个不同的值,y_

_ 是“我不再需要那个值”的约定。

基本相同:

y = pd.factorize(train['species'])[0]

除了此代码适用于任何具有至少 1 个元素的可索引返回值之外,而您的代码明确需要返回值中的两个项目。

关于python - y, _ assignment 在 python/sklearn 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21625655/

相关文章:

python : Find tuples from a list of tuples having duplicate data in the 0th element(of the tuple)

python - Python中有否定正则表达式(否定)吗?

machine-learning - 如何从惩罚逻辑回归的拟合管道中提取系数?

machine-learning - python 机器学习 弃用警告

python - Scipy 曲线拟合(优化)- 使用自定义函数对条件进行矢量化以识别阈值

python - 使用 BeautifulSoup 提取图像链接

python - 如何将 pytest fixture 应用于多个文件

python - 属性错误: module "sklearn.utils" has no attribute "_joblib" when inheriting class `sklearn.ensemble.BaggingClassifier.`

python - Sklearn 将字符串类标签更改为 int

python - python类继承的基本用法