예제 #1
0
def plot_rectangles(ax, single_example, plot_seq_width=1, offset=0, how='bar',
                    **plot_kwargs):
    """
    Parameters
    ----------
    ax : matplotlib axes
    single_example : numpy.ndarray
        A single example from within the batch.
        i.e. single_output = batch[seq_i]
        Shape = (3, n_outputs)
    plot_seq_width : int or float, optional
        The width of a sequence plotted on the X-axis.
        Multiply `left` and `right` values by `plot_seq_width` before plotting.
    offset : float, optional
        Shift rectangles left or right by `offset` where one complete sequence
        is of length `plot_seq_width`.  i.e. to move rectangles half a plot
        width right, set `offset` to `plot_seq_width / 2.0`.
    how : {'bar', 'line'}
    **plot_kwargs : key word arguments to send to `ax.bar()`.  For example:
        alpha : float, optional
            [0, 1].  Transparency for the rectangles.
        color
    """
    # sanity check
    for obj in [plot_seq_width, offset]:
        if not isinstance(obj, (int, float)):
            raise ValueError("Incorrect input: {}".format(obj))

    assert single_example.shape[0] == 3
    n_outputs = single_example.shape[1]
    colors = get_colors(n_outputs)
    for output_i in range(n_outputs):
        single_rect = single_example[:, output_i]

        # left
        left = (single_rect[0] * plot_seq_width) + offset
        right = (single_rect[1] * plot_seq_width) + offset

        # width
        if single_rect[0] > 0 and single_rect[1] > 0:
            width = (single_rect[1] - single_rect[0]) * plot_seq_width
        else:
            width = 0

        height = single_rect[2]
        color = colors[output_i]
        plot_kwargs.setdefault('color', color)

        if how == 'bar':
            plot_kwargs.setdefault('edgecolor', plot_kwargs['color'])
            plot_kwargs.setdefault('linewidth', 0)
            ax.bar(left, height, width, **plot_kwargs)
        elif how == 'line':
            ax.plot([left, left, right, right],
                    [0, height, height, 0],
                    **plot_kwargs)
        else:
            raise ValueError("'how' is not recognised.")
예제 #2
0
    def _plot_validation_scores_for_source_and_fold(self, ax, source_id, fold,
                                                    show_axes_labels,
                                                    show_scales):
        fields = ['iteration'] + ['scores.' + metric_name for metric_name in
                                  self.validation_metric_names]
        monary = Monary(host=self.mongo_host)
        result = monary.query(
            db=self.mongo_db,
            coll='validation_scores',
            query={
                'experiment_id': self.experiment_id,
                'source_id': source_id,
                'fold': fold
            },
            fields=fields,
            types=['int32'] + ['float32'] * len(self.validation_metric_names)
        )

        index = result[0]
        data = {metric_name: result[i+1] for i, metric_name in
                enumerate(self.validation_metric_names)}
        df = pd.DataFrame(data, index=index)
        df = df.sort_index()
        df = self._downsample(df)

        # Create multiple independent axes.  Adapted from Joe Kington's answer:
        # http://stackoverflow.com/a/7734614

        # Colours
        n = len(self.validation_metric_names)
        colors = get_colors(n)

        # Twin the x-axis to make independent y-axes.
        axes = [ax]
        for metric_name in self.validation_metric_names[1:]:
            axes.append(ax.twinx())

        SEP = 0.2
        if show_scales:
            for i, axis in enumerate(axes):
                axis.yaxis.tick_right()
                if i != 0:
                    # To make the border of the right-most axis visible,
                    # we need to turn the frame on. This hides the other plots,
                    # however, so we need to turn its fill off.
                    axis.set_frame_on(True)
                    axis.patch.set_visible(False)
                    # Move the last y-axes spines over to the right.
                    axis.spines['right'].set_position(
                        ('axes', 1 + (SEP * i)))
        else:
            for axis in axes:
                axis.tick_params(labelright=False, labelleft=False)
                axis.yaxis.set_ticks_position('none')
                axis.spines['right'].set_visible(False)

        for axis in axes:
            for spine in ['top', 'left', 'bottom']:
                axis.spines[spine].set_visible(False)
            axis.xaxis.set_ticks_position('none')

        lines = []
        for i, (axis, metric_name, color) in enumerate(
                zip(axes, self.validation_metric_names, colors)):
            axis.tick_params(axis='y', colors=color, direction='out')
            label = metric_name.replace("regression.", "")
            label = label.replace("classification_", "")
            label = label.replace("_", " ")
            label = label.replace(".", " ")
            label = label.replace(" ", "\n")
            line, = axis.plot(
                df.index, df[metric_name].values, color=color, label=label)
            if show_axes_labels and show_scales:
                axis.set_ylabel(
                    label, color=color, rotation=0, fontsize=8, va='bottom')
                if i == 0:
                    coords = (1.05, 1.1)
                else:
                    coords = (1.05 + (SEP * i), 1.1)
                axis.yaxis.set_label_coords(*coords)
            lines.append(line)

        self._last_iteration_processed['validation'] = index[-1]
        return lines
예제 #3
0
    def _plot_validation_scores_for_source_and_fold(self, ax, source_id, fold,
                                                    show_axes_labels,
                                                    show_scales):
        fields = ['iteration'] + [
            'scores.' + metric_name
            for metric_name in self.validation_metric_names
        ]
        monary = Monary(host=self.mongo_host)
        result = monary.query(db=self.mongo_db,
                              coll='validation_scores',
                              query={
                                  'experiment_id': self.experiment_id,
                                  'source_id': source_id,
                                  'fold': fold
                              },
                              fields=fields,
                              types=['int32'] +
                              ['float32'] * len(self.validation_metric_names))

        index = result[0]
        data = {
            metric_name: result[i + 1]
            for i, metric_name in enumerate(self.validation_metric_names)
        }
        df = pd.DataFrame(data, index=index)
        df = df.sort_index()
        df = self._downsample(df)

        # Create multiple independent axes.  Adapted from Joe Kington's answer:
        # http://stackoverflow.com/a/7734614

        # Colours
        n = len(self.validation_metric_names)
        colors = get_colors(n)

        # Twin the x-axis to make independent y-axes.
        axes = [ax]
        for metric_name in self.validation_metric_names[1:]:
            axes.append(ax.twinx())

        SEP = 0.2
        if show_scales:
            for i, axis in enumerate(axes):
                axis.yaxis.tick_right()
                if i != 0:
                    # To make the border of the right-most axis visible,
                    # we need to turn the frame on. This hides the other plots,
                    # however, so we need to turn its fill off.
                    axis.set_frame_on(True)
                    axis.patch.set_visible(False)
                    # Move the last y-axes spines over to the right.
                    axis.spines['right'].set_position(('axes', 1 + (SEP * i)))
        else:
            for axis in axes:
                axis.tick_params(labelright=False, labelleft=False)
                axis.yaxis.set_ticks_position('none')
                axis.spines['right'].set_visible(False)

        for axis in axes:
            for spine in ['top', 'left', 'bottom']:
                axis.spines[spine].set_visible(False)
            axis.xaxis.set_ticks_position('none')

        lines = []
        for i, (axis, metric_name, color) in enumerate(
                zip(axes, self.validation_metric_names, colors)):
            axis.tick_params(axis='y', colors=color, direction='out')
            label = metric_name.replace("regression.", "")
            label = label.replace("classification_", "")
            label = label.replace("_", " ")
            label = label.replace(".", " ")
            label = label.replace(" ", "\n")
            line, = axis.plot(df.index,
                              df[metric_name].values,
                              color=color,
                              label=label)
            if show_axes_labels and show_scales:
                axis.set_ylabel(label,
                                color=color,
                                rotation=0,
                                fontsize=8,
                                va='bottom')
                if i == 0:
                    coords = (1.05, 1.1)
                else:
                    coords = (1.05 + (SEP * i), 1.1)
                axis.yaxis.set_label_coords(*coords)
            lines.append(line)

        self._last_iteration_processed['validation'] = index[-1]
        return lines
예제 #4
0
def plot_rectangles(ax,
                    single_example,
                    plot_seq_width=1,
                    offset=0,
                    how='bar',
                    **plot_kwargs):
    """
    Parameters
    ----------
    ax : matplotlib axes
    single_example : numpy.ndarray
        A single example from within the batch.
        i.e. single_output = batch[seq_i]
        Shape = (3, n_outputs)
    plot_seq_width : int or float, optional
        The width of a sequence plotted on the X-axis.
        Multiply `left` and `right` values by `plot_seq_width` before plotting.
    offset : float, optional
        Shift rectangles left or right by `offset` where one complete sequence
        is of length `plot_seq_width`.  i.e. to move rectangles half a plot
        width right, set `offset` to `plot_seq_width / 2.0`.
    how : {'bar', 'line'}
    **plot_kwargs : key word arguments to send to `ax.bar()`.  For example:
        alpha : float, optional
            [0, 1].  Transparency for the rectangles.
        color
    """
    # sanity check
    for obj in [plot_seq_width, offset]:
        if not isinstance(obj, (int, float)):
            raise ValueError("Incorrect input: {}".format(obj))

    assert single_example.shape[0] == 3
    n_outputs = single_example.shape[1]
    colors = get_colors(n_outputs)
    for output_i in range(n_outputs):
        single_rect = single_example[:, output_i]

        # left
        left = (single_rect[0] * plot_seq_width) + offset
        right = (single_rect[1] * plot_seq_width) + offset

        # width
        if single_rect[0] > 0 and single_rect[1] > 0:
            width = (single_rect[1] - single_rect[0]) * plot_seq_width
        else:
            width = 0

        height = single_rect[2]
        color = colors[output_i]
        plot_kwargs.setdefault('color', color)

        if how == 'bar':
            plot_kwargs.setdefault('edgecolor', plot_kwargs['color'])
            plot_kwargs.setdefault('linewidth', 0)
            ax.bar(left, height, width, **plot_kwargs)
        elif how == 'line':
            ax.plot([left, left, right, right], [0, height, height, 0],
                    **plot_kwargs)
        else:
            raise ValueError("'how' is not recognised.")