| 98 | |
| 99 | |
| 100 | def plot_features_strength(model, height_per_feature=0.5, width_per_plot=5, plots_per_row=None): |
| 101 | with _import_matplotlib() as _plt: |
| 102 | plt = _plt |
| 103 | strengths = calc_features_strength(model) |
| 104 | dimension = len(strengths[0]) |
| 105 | features = len(strengths) |
| 106 | if not plots_per_row: |
| 107 | plots_per_row = min(5, dimension) |
| 108 | rows = int(math.ceil(dimension / plots_per_row)) |
| 109 | fig, axes = plt.subplots(rows, plots_per_row) |
| 110 | if rows == 1: |
| 111 | axes = [axes] |
| 112 | if plots_per_row == 1: |
| 113 | axes = [[row_axes] for row_axes in axes] |
| 114 | fig.suptitle("Features Strength") |
| 115 | fig.set_size_inches(width_per_plot * plots_per_row, height_per_feature * features * rows) |
| 116 | |
| 117 | for dim in range(dimension): |
| 118 | strengths = [(s[dim], i) for i, s in enumerate(strengths)] |
| 119 | # strengths = list(reversed(sorted(strengths))) |
| 120 | strengths = list(sorted(strengths)) |
| 121 | labels = ["Feature #{}".format(f) for _, f in strengths] |
| 122 | strengths = [s for s, _ in strengths] |
| 123 | |
| 124 | ax = axes[dim // plots_per_row][dim % plots_per_row] |
| 125 | colors = [(1, 0, 0) if s > 0 else (0, 0, 1) for s in strengths] |
| 126 | ax.set_title("Dimension={}".format(dim)) |
| 127 | ax.barh(range(len(strengths)), strengths, align='center', color=colors) |
| 128 | ax.set_yticks(range(len(strengths))) |
| 129 | ax.set_yticklabels(labels) |
| 130 | # ax.invert_yaxis() # labels read top-to-bottom |
| 131 | ax.set_xlabel('Prediction value change') |
| 132 | |
| 133 | return fig |