python - 特征和权重的热图

标签 python matplotlib heatmap

我运行了机器学习算法。现在我有一个系列,其索引=结果模型的特征,列是相应的权重。

我想将特征及其权重显示为热图,其中我想将高权重的特征显示得比权重较轻的特征更暗。是否也可以用与负权重不同的颜色显示正权重?与所有具有正权重(如绿色)的特征一样,在正权重内可以根据权重值具有深色、浅色,而所有负权重特征为红色,并且负权重再次使颜色强度相对于绝对值发生变化。

这是典型的特征权重矩阵的样子。它是一个以索引为特征的系列。

adm_hr_ls_7                                            [-0.0151751599842]
admittype_elective                                     [-0.0767214648205]
admission_age_inyears                                    [0.629567909855]
patient_race_caucasian                                    [-0.0543069188]
gender_female                                          [-0.0831126807492]
marital_status_married                                 [-0.0219135568879]
religion_none                                          [-0.0629291312093]
employmentstatus_retired                                [0.0620868529898]
employmentstatus_not_employed                           [0.0195733078954]

编辑:

你的代码给了我这样的东西

enter image description here

我正在寻找一个网格,其中所有顶部的正特征都显示为由权重的绝对值引导的颜色强度。所有正权重都具有不同强度的一种颜色。类似地,所有顶部负权重(同样是abs术语中的顶部)将具有与abs权重大小相对应的不同强度的一种颜色。您的代码首先无法正确对齐标签。其次,它提供了很多颜色。

可以说这就是数据。

admission_age_inyears                                           [3.86703690989]
emergencydepartmentlengthofstayminutes                          [3.84708584711]
current_los_from_admissions                                     [3.83956976064]
total_time_in_progressive_inpatient                             [3.63955027973]
total_time_spent_inpatient                                      [2.59339330312]
nbr_of_hosp_last_90_days                                        [2.44570139977]
total_time_spent_in_er                                          [2.37914969651]
prior_admittype_emergency                                       [2.18467109815]
nbr_inpatient_visits                                            [2.09615621507]
curr_rx_gen_atorvastatin_calcium                                [2.08752966479]
substanceusehistory                                             [1.91340885366]
timetofirstnurseminutes  
to_be_discharged_to_hospice                                   [-0.323042070071]
tot_est_median_age_years                                       [-0.33548236033]
total_current_pharma_laxatives                                [-0.348768315972]
curr_rx_gen_rivaroxaban                                       [-0.359848868739]
dis_notes_contact_info                                        [-0.360264143656]
total_speak_indo_european                                     [-0.373310297224]
patient_race_african_american                                 [-0.391335453176]
financialclass_commercial                                     [-0.427463083689]
curr_rx_gen_epinephrine_hcl                                    [-0.44205667523]
tot_est_age_55_to_64_years                                    [-0.451699358283]
percent_high_school_grad_or_higher                            [-0.461380248502]
tot_est_age_65_to_74_years      

我想要的是前 10-15 个正权重应该由一种常见颜色(比如说绿色)表示,这样每个特征的颜色强度由相应特征权重的绝对值定义。类似地,所有负权重特征(前 10-15 个)应由一种常见颜色(如红色)表示,并且颜色的强度由相应特征权重的绝对值定义

编辑II enter image description here

编辑3:

我运行了这段代码。出现错误

n_features = 50

feature_names = ["feature_"+str(i) for i in range(n_features)]
weights = coef_lren.values

# select top 15 high and low features
indices = np.argsort(np.abs(weights))
n_top = 15
top = np.hstack((indices[:n_top], indices[-n_top:]))[::-1]

vmax = np.abs(weights).max()

plt.clf()
plt.imshow(weights[top].reshape((-1,1)),interpolation='nearest', cmap="seismic", vmin=-vmax, vmax=vmax)
plt.axes().xaxis.set_visible(False)
plt.colorbar()

tick_marks = np.arange(2 * n_top)
plt.yticks(tick_marks, [feature_names[i] for i in top])

   433             not np.can_cast(self._A.dtype, np.float)):
--> 434             raise TypeError("Image data can not convert to float")


TypeError: Image data can not convert to float

最佳答案

实际上还有一点点工作要做,这应该会给你带来好的结果:

# define the range for the color mapping
# make sure the color map is centered on 0
# >> use maximum absolute value and not the real min and max (default behaviou)
vmax = np.abs(my_weights).max()

plt.imshow(my_weights.reshape((-1,1)), cmap="seismic", vmin=-vmax, vmax=vmax)

# add feature names
feature_names = ['foo', 'bar', ...]
tick_marks = np.arange(len(feature_names))
plt.yticks(tick_marks, feature_names) 

编辑:

import numpy as np
from matplotlib import pyplot as plt 

n_features = 50

feature_names = ["feature_"+str(i) for i in range(n_features)]
weights = np.random.randn(n_features)

# select top 15 high and low features
indeces = np.argsort(weights)
n_top = 15
top = np.hstack((indeces[:n_top], indeces[-n_top:]))[::-1]

vmax = np.abs(weights).max()

plt.clf()
plt.imshow(weights[top].reshape((-1,1)),interpolation='nearest', cmap="seismic", vmin=-vmax, vmax=vmax)
plt.axes().xaxis.set_visible(False)
plt.colorbar()

tick_marks = np.arange(2 * n_top)
plt.yticks(tick_marks, [feature_names[i] for i in top]) 

result

关于python - 特征和权重的热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125852/

相关文章:

r - 如果该组的每个样本的阈值均高于该阈值,则选择数据集中的值

python - 是否有理由更喜欢 __slots__ 的列表或元组?

python - 如何避免在此递归函数中使用全局变量并改进我的代码?

python - IPython %timeit 魔术 - 将输出从 "mean & std"更改为 "best of 3"

python - 来自按级别分组的多索引 Pandas 数据框的子图

python - 保存交互式 Matplotlib 图形

python - 不在 matplotlib 中绘制 'zero' 或将零更改为无 [Python]

python - 在 MatPlotLib 中添加下拉列表和文本框,并根据输入显示绘图

带有来自 3D 数据集的热图的 gnuplot 2D 极坐标图 - 可能吗?