注意
转到末尾 下载完整的示例代码或通过 JupyterLite 或 Binder 在浏览器中运行此示例。
绘制随机生成的多标签数据集#
这说明了 make_multilabel_classification 数据集生成器。每个样本包含两个特征(总共最多 50 个)的计数,这些特征在两个类中的分布不同。
点的标签如下所示,其中 Y 表示该类存在
1 |
2 |
3 |
颜色 |
|---|---|---|---|
Y |
N |
N |
红色 |
N |
Y |
N |
蓝色 |
N |
N |
Y |
黄色 |
Y |
Y |
N |
紫色 |
Y |
N |
Y |
橙色 |
Y |
Y |
N |
绿色 |
Y |
Y |
Y |
棕色 |
星号标记了每个类的预期样本;它的大小反映了选择该类标签的概率。
左侧和右侧的示例突出显示了 n_labels 参数:右侧图中的更多样本具有 2 个或 3 个标签。
请注意,这个二维示例非常退化:通常特征的数量远大于“文档长度”,而在这里我们的文档比词汇量大得多。同样,对于 n_classes > n_features,特征区分特定类的可能性要小得多。

The data was generated from (random_state=939):
Class P(C) P(w0|C) P(w1|C)
red 0.52 0.46 0.54
blue 0.28 0.59 0.41
yellow 0.19 0.50 0.50
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_multilabel_classification as make_ml_clf
COLORS = np.array(
[
"!",
"#FF3333", # red
"#0198E1", # blue
"#BF5FFF", # purple
"#FCD116", # yellow
"#FF7216", # orange
"#4DBD33", # green
"#87421F", # brown
]
)
# Use same random seed for multiple calls to make_multilabel_classification to
# ensure same distributions
RANDOM_SEED = np.random.randint(2**10)
def plot_2d(ax, n_labels=1, n_classes=3, length=50):
X, Y, p_c, p_w_c = make_ml_clf(
n_samples=150,
n_features=2,
n_classes=n_classes,
n_labels=n_labels,
length=length,
allow_unlabeled=False,
return_distributions=True,
random_state=RANDOM_SEED,
)
ax.scatter(
X[:, 0], X[:, 1], color=COLORS.take((Y * [1, 2, 4]).sum(axis=1)), marker="."
)
ax.scatter(
p_w_c[0] * length,
p_w_c[1] * length,
marker="*",
linewidth=0.5,
edgecolor="black",
s=20 + 1500 * p_c**2,
color=COLORS.take([1, 2, 4]),
)
ax.set_xlabel("Feature 0 count")
return p_c, p_w_c
_, (ax1, ax2) = plt.subplots(1, 2, sharex="row", sharey="row", figsize=(8, 4))
plt.subplots_adjust(bottom=0.15)
p_c, p_w_c = plot_2d(ax1, n_labels=1)
ax1.set_title("n_labels=1, length=50")
ax1.set_ylabel("Feature 1 count")
plot_2d(ax2, n_labels=3)
ax2.set_title("n_labels=3, length=50")
ax2.set_xlim(left=0, auto=True)
ax2.set_ylim(bottom=0, auto=True)
plt.show()
print("The data was generated from (random_state=%d):" % RANDOM_SEED)
print("Class", "P(C)", "P(w0|C)", "P(w1|C)", sep="\t")
for k, p, p_w in zip(["red", "blue", "yellow"], p_c, p_w_c.T):
print("%s\t%0.2f\t%0.2f\t%0.2f" % (k, p, p_w[0], p_w[1]))
脚本总运行时间: (0 minutes 0.110 seconds)
相关示例