0

背景

我正在阅读Python 机器学习简介,并在第 2 章中尝试了 In[45] 的可视化。首先,我使用不同的参数LogisticRegression为 Winsconsin 癌症数据集拟合了 3 个分类器。C然后,对于每个分类器,我绘制了每个特征的系数大小。

%matplotlib inline
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot as plt

cancer = load_breast_cancer()

for C, marker in [(0.01, 'o'), (1., '^'), (100., 'v')]:
    logreg = LogisticRegression(C=C).fit(cancer.data, cancer.target)
    plt.plot(logreg.coef_[0], marker, label=f"C={C}")
plt.xticks(range(cancer.data.shape[1]), cancer.feature_names, rotation=90)
plt.hlines(0, 0, cancer.data.shape[1])
plt.legend()

按标记绘制

在这种情况下,我更喜欢 barplot 而不是使用标记。我想得到一个图表,例如:

条形图

我通过以下工作流程实现了这一点。

第 1 步:创建一个DataFrame保持系数幅值作为一行

%matplotlib inline
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
import pandas as pd

cancer = load_breast_cancer()

df = pd.DataFrame(columns=cancer.feature_names)
for C in [0.01, 1., 100.]:
    logreg = LogisticRegression(C=C).fit(cancer.data, cancer.target)
    df.loc[f"C={C}"] = logreg.coef_[0]

df

特征数据框

第 2 步:将其转换DataFrameseaborn.barplot适用的形式

import itertools

df_bar = pd.DataFrame(columns=['C', 'Feature', 'Coefficient magnitude'])
for C, feature in itertools.product(df.index, df.columns):
    magnitude = df.at[C, feature]
    df_bar = df_bar.append({'C': C, 'Feature': feature, 'Coefficient magnitude': magnitude},
                           ignore_index=True)

df_bar.head()

条形图的数据框

第 3 步:绘制依据seaborn.barplot

from matplotlib import pyplot as plt
import seaborn as sns

plt.figure(figsize=(12,8))
sns.barplot(x='Feature', y='Coefficient magnitude', hue='C', data=df_bar)
plt.xticks(rotation=90)

这产生了我想要的图表。

问题

我认为第 2 步很乏味。我可以df直接从步骤 1 中制作条形图还是df_bar通过单线制作?还是有更优雅的工作流程来获取条形图?

4

1 回答 1

3

Pandas 将条形图按列分组。因此应该可以做到

df = df.transpose()
df.plot(kind="bar")

不使用seaborn。

如果出于任何原因需要使用 seaborn,则问题中的 step2 可能可以通过pandas.melt.

df_bar = df.reset_index().melt(id_vars=["index"])
sns.barplot(x="variable", y="value", hue="index", data=df_bar)
于 2018-06-19T10:13:37.960 回答