背景
我正在阅读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 步:将其转换DataFrame
为seaborn.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
通过单线制作?还是有更优雅的工作流程来获取条形图?