Ejemplo n.º 1
0
def _plot_contours(
        ax: plt.Axes,
        clf: Union[sklearn.svm.SVC, sklearn.svm.LinearSVC],
        xx: np.ndarray,
        yy: np.ndarray,
        **kwargs: Optional
) -> None:
    """
    Plot the decision boundaries for a classifier.
    :param ax: plt.Axes, axis to plot onto
    :param clf: Union[sklearn.svm.SVC, sklearn.svm.LinearSVC], sklearn classifiers
    :param xx: np.ndarray, x values to plot onto
    :param yy: np.ndarray, y values to plot onto
    :param kwargs: Optional, kwargs
    :return: None
    """
    z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    z = z.reshape(xx.shape)

    ax.contourf(xx, yy, z, **kwargs)

    return None
def plot_chm_contour(chm: np.ndarray,
                     ax: plt.Axes = None,
                     **kwargs) -> plt.Axes:
    "Plot chm as contour function"
    if ax is None: fig, ax = plt.subplots(figsize=figsize)
    xs = range(chm.shape[-2])
    ys = range(chm.shape[-1], 0, -1)
    X, Y = np.meshgrid(xs, ys)
    top = np.amax(chm)
    bot = np.amin(chm)
    cs = ax.contourf(X,
                     Y,
                     chm,
                     levels=np.linspace(bot, top, num=100, endpoint=True))
    return ax
Ejemplo n.º 3
0
def kde_plot(axes: plt.Axes, x: np.ndarray, y: np.ndarray, **kwargs):

	kde_results = utils.kde_2d(x, y, **kwargs)
	clevels = axes.contourf(*kde_results, 10, cmap='YlGn_r')

	# Delete outer levels
	for level in clevels.collections:
		for kp, path in reversed(list(enumerate(level.get_paths()))):
			verts = path.vertices  # (N,2)-shape array of contour line coordinates
			diameter = np.max(verts.max(axis=0) - verts.min(axis=0))
			dataset_diameter = max([(x.max()-x.min()), (y.max()-y.min())])
			if diameter > 0.75*dataset_diameter:
				del (level.get_paths()[kp])

	# Identify points within contours
	inside = np.full_like(x, False, dtype=bool)
	for level in clevels.collections:
		for kp, path in reversed(list(enumerate(level.get_paths()))):
			inside |= path.contains_points(tuple(zip(*(x,y))))
	ax.scatter(x[~inside], y[~inside], marker='.', color='g', s=2, alpha=0.1)
Ejemplo n.º 4
0
def class_contour(x: np.array,
                  y: np.array,
                  clf: nn.Module,
                  prec: float = 0.05,
                  title: str = "Class Contour",
                  ax: plt.Axes = None):
    """ Plots the class contour IF the dimnesions is 2 or lower.
        Otherwise the embeddings are visualized using TSNE.

        Paramters:
            x: np.array
                Feature matrix.
            y: np.array
                Labels for the x.
            clf: nn.Module
                Downstream classifier.
            prec: float
                Precision of the mesh grid (if it is created, i.e. when input dim is <=2)
            title: str
                Title of the plot.
            ax: matplotlib.Axes
                Axes for the plot. If None a new axis is created.
        Return:
            matplotlib.Figure: Figure of the plot IF the axis paramter is None.
            Otherwise nothing is returned.

    """
    if isinstance(x, torch.Tensor):
        x = x.detach().cpu().numpy()
    if isinstance(y, torch.Tensor):
        y = y.detach().cpu().numpy()

    if len(x.shape) != 2:
        x = np.array(list(x))
    if len(y.shape) != 2:
        y = np.array(list(y))

    fig = None
    if ax is None:
        fig, ax = plt.subplots(figsize=(5, 5))

    clf_device = clf.device

    mode = ""
    try:
        h = prec  # step size in the mesh
        x_min, x_max = x[:, 0].min() - 0, x[:, 0].max() + min(h, 0)
        y_min, y_max = x[:, 1].min() - 0, x[:, 1].max() + min(h, 0)

        # np.linspace(2.0, 3.0, num=5)
        xx, yy = np.meshgrid(
            np.linspace(x_min, x_max, num=int((x_max - x_min) // h)),
            np.linspace(y_min, y_max, num=int((y_max - y_min) // h)))

        clf = clf.cpu()
        Z = clf(
            torch.tensor(
                np.c_[xx.ravel(), yy.ravel()],
                dtype=torch.float32).detach().cpu()).detach().cpu().numpy()

        Z = np.argmax(Z, axis=1)
        Z = Z.reshape(xx.shape)

        Z = ndimage.gaussian_filter(Z, sigma=1.0, order=0)

        ax.contourf(xx,
                    yy,
                    Z,
                    alpha=0.8,
                    cmap=sns.color_palette("Spectral", as_cmap=True))
    except:
        # mode = " - TSNE"
        # x = TSNE(n_components=2).fit_transform(x)
        mode = " - PCA"
        x = PCA(n_components=2).fit_transform(x)

    ax.scatter(x[:, 0],
               x[:, 1],
               c=y.astype(int),
               cmap=sns.color_palette("Spectral", as_cmap=True),
               edgecolors='w')

    ax.set_title(f"{title} (Sample Shape: {x.shape}) {mode}")

    clf = clf.to(clf_device)

    if fig is not None:
        return fig