Exemplo n.º 1
0
def show_example(name_frame='F(1a)',
                 name_scene='E(1)',
                 N=1000,
                 N_supression=0):
    """
    Plots the GT, output and ,,binary'' colormap for the example figure
    Fig.5
    
    parameters:
        name_frame: name of the source image (inductive scenario)
        name_scene: name of the output image
        N: no. vectors in the 2nd stage as int or percentage string e.g. '33p'
        N_supression: no. supressed vectors (extension of the algorithm, unused)
    """
    for i_f, f in enumerate(['scene', 'frame', 'exbl']):
        plt.rcParams.update({'font.size': 14})
        fname = "res/{}_{}_{}_{}_{}.npz".format(name_frame, name_scene, N,
                                                N_supression, f)
        print(fname)
        res = np.load(fname)
        pred = res['pred_2'] if f == 'exbl' else res['pred_1']
        n_t = np.count_nonzero(res['anno'] == 1)
        pp = np.ravel(pred)
        arg = np.argsort(pp)[::-1]
        tresh = pp[arg][n_t]
        truth = np.zeros_like(res['anno'])
        truth[res['anno'] == 1] = 1
        bin_res = np.zeros_like(res['anno'])
        bin_res[pred > tresh] = 1

        final_res = np.zeros_like(res['anno'])
        final_res[np.logical_and(bin_res == 1, truth == 1)] = 1  #TP
        final_res[np.logical_and(bin_res == 0, truth == 1)] = 2  #FN
        final_res[np.logical_and(bin_res == 1, truth == 0)] = 3  #FP

        colors = 'white red #3399ff #d3d3d3'.split()
        cmap = ListedColormap(colors, name='colors', N=4)

        plt.imsave('res\example_bin_{}.pdf'.format(f), final_res, cmap=cmap)

        if f == 'scene':
            ax = plt.subplot()
            plt.rcParams.update({'font.size': 14})
            im = plt.imshow(res['pred_1'],
                            cmap='Reds',
                            interpolation='nearest',
                            aspect='auto')
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.02)
            plt.colorbar(im, cax=cax)
            plt.tight_layout()
            plt.savefig("res\example_pred.pdf",
                        bbox_inches='tight',
                        pad_inches=0)
            plt.close()

        plt.rcParams.update({'font.size': 14})
        anno = res['anno']
        anno[anno == 15] = 0

        colors = ['white', 'red']
        for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
            colors.append(plt.get_cmap('tab10')(i / 10))
        cmap = ListedColormap(colors, name='colors', N=len(colors))
        plt.imsave('res\example_gt.pdf', anno, cmap=cmap)
clf = LogisticRegression()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
cm = confusion_matrix(y_test, y_pred)

plt.figure()
from matplotlib.colors import ListedColormap

X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(X_set[:,0].min() - 1, 
                               X_set[:,0].max() + 1, 
                               step = 0.01),
                     np.arange(X_set[:,1].min() - 1, 
                               X_set[:,1].max() + 1, 
                               step = 0.001))
boundary = clf.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape)
plt.contourf(X1, X2, boundary, alpha = 0.75, 
             cmap = ListedColormap(('#fc7a74', '#6ff785')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i,j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set==j, 1],
                c = ListedColormap(('red', 'green'))(i), 
                label = j, s = 40)
plt.title('Logistic regression classifier')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.legend()
plt.show()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title(' Random Forest Classifier (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
Exemplo n.º 4
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets

from frlearn.base import select_class
from frlearn.classifiers import FRNN
from frlearn.utils.owa_operators import additive, strict

# Import example data and reduce to 2 dimensions.
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target

# Define color maps.
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

# Initialise figure with wide aspect for two side-by-side subfigures.
plt.figure(figsize=(8, 4))

for i, owa_weights, k in [(1, strict(), 1), (2, additive(), 20)]:
    axes = plt.subplot(1, 2, i)

    # Create an instance of the FRNN classifier and construct the model.
    clf = FRNN(upper_weights=owa_weights,
               lower_weights=owa_weights,
               upper_k=k,
               lower_k=k)
    model = clf(X, y)
# In[18]:

X_set, Y_set = x_train, y_train
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('0.5', '0.75')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(Y_set)):
    plt.scatter(X_set[Y_set == j, 0],
                X_set[Y_set == j, 1],
                c=ListedColormap(('0', '1'))(i),
                label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.legend()
plt.show()

# In[19]:
Exemplo n.º 6
0
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0],
                X_set[y_set == j, 1],
                c=ListedColormap(('orange', 'blue'))(i),
                label=j)
plt.title('SVM (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
#graphing the sets to visualize the training data and model
from matplotlib.colors import ListedColormap
x_set, y_set = x_train, y_train
x1, x2 = np.meshgrid(
    np.arange(start=x_set[:, 0].min() - 1,
              stop=x_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=x_set[:, 1].min() - 1,
              stop=x_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(x1,
             x2,
             classifier.predict(np.array([x1.ravel(),
                                          x2.ravel()]).T).reshape(x1.shape),
             alpha=0.75,
             cmap=ListedColormap(('blue', 'yellow')))
plt.xlim(x1.min(), x1.max())
plt.ylim(x2.min(), x2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(x_set[y_set == j, 0],
                x_set[y_set == j, 1],
                c=ListedColormap(('blue', 'yellow'))(i),
                label=j,
                edgecolors="black")
plt.title('Random Forest (training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.show()

#graphing the sets to visualize the test data and model
from matplotlib.colors import ListedColormap
def plot_boundaries_SVM(X_train,
                        y_train,
                        score=None,
                        class_func=None,
                        support_vectors=None,
                        degree=None,
                        n_colors=100,
                        mesh_res=1000,
                        ax=None):
    X = X_train  #np.vstack((X_test, X_train))
    margin_x = (X[:, 0].max() - X[:, 0].min()) * 0.05
    margin_y = (X[:, 1].max() - X[:, 1].min()) * 0.05
    x_min, x_max = X[:, 0].min() - margin_x, X[:, 0].max() + margin_x
    y_min, y_max = X[:, 1].min() - margin_y, X[:, 1].max() + margin_y
    hx = (x_max - x_min) / mesh_res
    hy = (y_max - y_min) / mesh_res
    x_domain = np.arange(x_min, x_max, hx)
    y_domain = np.arange(y_min, y_max, hy)
    xx, yy = np.meshgrid(x_domain, y_domain)

    if ax is None:
        ax = plt.subplot(1, 1, 1)

    cm = plt.cm.RdBu
    cm_bright = ListedColormap(['#FF0000', '#0000FF'])

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    if class_func is not None:
        if degree is not None:
            polynomial_set = get_polynimial_set(np.c_[xx.ravel(),
                                                      yy.ravel()],
                                                degree=degree)
            Z = class_func(polynomial_set)[:, 1]
        else:
            Z_aux = class_func(np.c_[xx.ravel(), yy.ravel()])
            Z = Z_aux[:, 1]

        # Put the result into a color plot
        Z = Z.reshape(xx.shape)

        cf = ax.contourf(xx,
                         yy,
                         Z,
                         n_colors,
                         vmin=0.,
                         vmax=1.,
                         cmap=cm,
                         alpha=.8)
        plt.colorbar(cf, ax=ax)
        #plt.colorbar(Z,ax=ax)

        boundary_line = np.where(np.abs(Z - 0.5) < 0.001)

        ax.scatter(x_domain[boundary_line[1]],
                   y_domain[boundary_line[0]],
                   color='k',
                   alpha=0.5,
                   s=1)
        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.text(xx.max() - .3,
                yy.min() + .3, ('%.2f' % score).lstrip('0'),
                size=40,
                horizontalalignment='right')

    # Plot also the training points
    ax.scatter(X_train[:, 0],
               X_train[:, 1],
               c=y_train,
               cmap=cm_bright,
               edgecolors='k',
               s=100,
               marker='o')
    ax.scatter(support_vectors[:, 0],
               support_vectors[:, 1],
               c='y',
               edgecolors='k',
               s=30,
               marker='o')
Exemplo n.º 9
0
    [0.678489, 0.863742, 0.189503], [0.688944, 0.865448, 0.182725],
    [0.699415, 0.867117, 0.175971], [0.709898, 0.868751, 0.169257],
    [0.720391, 0.870350, 0.162603], [0.730889, 0.871916, 0.156029],
    [0.741388, 0.873449, 0.149561], [0.751884, 0.874951, 0.143228],
    [0.762373, 0.876424, 0.137064], [0.772852, 0.877868, 0.131109],
    [0.783315, 0.879285, 0.125405], [0.793760, 0.880678, 0.120005],
    [0.804182, 0.882046, 0.114965], [0.814576, 0.883393, 0.110347],
    [0.824940, 0.884720, 0.106217], [0.835270, 0.886029, 0.102646],
    [0.845561, 0.887322, 0.099702], [0.855810, 0.888601, 0.097452],
    [0.866013, 0.889868, 0.095953], [0.876168, 0.891125, 0.095250],
    [0.886271, 0.892374, 0.095374], [0.896320, 0.893616, 0.096335],
    [0.906311, 0.894855, 0.098125], [0.916242, 0.896091, 0.100717],
    [0.926106, 0.897330, 0.104071], [0.935904, 0.898570, 0.108131],
    [0.945636, 0.899815, 0.112838], [0.955300, 0.901065, 0.118128],
    [0.964894, 0.902323, 0.123941], [0.974417, 0.903590, 0.130215],
    [0.983868, 0.904867, 0.136897], [0.993248, 0.906157, 0.143936]
]

from matplotlib.colors import ListedColormap

cmaps = {}
for (name, data) in (('magma', _magma_data), ('inferno', _inferno_data),
                     ('plasma', _plasma_data), ('viridis', _viridis_data)):

    cmaps[name] = ListedColormap(data, name=name)

magma = cmaps['magma']
inferno = cmaps['inferno']
plasma = cmaps['plasma']
viridis = cmaps['viridis']
Exemplo n.º 10
0
from matplotlib.pyplot import get_cmap
from matplotlib.pyplot import cm
from matplotlib.colors import ListedColormap
from matplotlib.colors import BoundaryNorm

rgb_colors = []
rgb_colors.append((49, 0, 241))  #1 indigo
rgb_colors.append((66, 255, 35))  #2 ltgreen
rgb_colors.append((50, 202, 25))  #3 green
rgb_colors.append((33, 146, 14))  #4 dkgreen
rgb_colors.append((249, 252, 45))  #5 yellow
rgb_colors.append((224, 191, 35))  #6 yellow-orange
rgb_colors.append((247, 148, 32))  #7 orange
rgb_colors.append((243, 0, 25))  #8 ltred

colors = []
for atup in rgb_colors:
    colors.append('#%02x%02x%02x' % atup)

cm.register_cmap(cmap=ListedColormap(colors, 'ltg'))

cmap = get_cmap('radar')
cmap.set_under('#e3e3e3')  #(227,227,227)

bounds = [0.1, 2.5, 5, 7.5, 10, 20, 30, 40, 50]
norm = BoundaryNorm(bounds, cmap.N)
def plot_boundaries_keras(X_train,
                          y_train,
                          score,
                          probability_func,
                          model_vals=None,
                          degree=None,
                          bias=False,
                          h=.02,
                          ax=None,
                          margin=0.5,
                          mesh_res=500,
                          activation='sigmoid'):
    colors = ['g', 'w', 'y', 'b']
    X = X_train
    margin_x = (X[:, 0].max() - X[:, 0].min()) * margin
    margin_y = (X[:, 1].max() - X[:, 1].min()) * margin
    x_min, x_max = X[:, 0].min() - margin_x, X[:, 0].max() + margin_x
    y_min, y_max = X[:, 1].min() - margin_y, X[:, 1].max() + margin_y
    hx = (x_max - x_min) / mesh_res
    hy = (y_max - y_min) / mesh_res
    x_domain = np.arange(x_min, x_max, hx)
    y_domain = np.arange(y_min, y_max, hy)
    xx, yy = np.meshgrid(x_domain, y_domain)

    if ax is None:
        ax = plt.subplot(1, 1, 1)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].

    if degree is not None:
        polynomial_set = get_polynimial_set(np.c_[xx.ravel(),
                                                  yy.ravel()],
                                            degree=degree,
                                            bias=bias)
        Zaux = probability_func(polynomial_set)
    else:
        Zaux = probability_func(np.c_[xx.ravel(), yy.ravel()])
        # Z = Z_aux[:, 1]
    print(Zaux.shape)

    if Zaux.shape[1] == 2:
        Z = Zaux[:, 1]
    else:
        Z = Zaux[:, 0]

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)

    cm = plt.cm.RdBu
    cm_bright = ListedColormap(['#FF0000', '#0000FF'])

    cf = ax.contourf(xx, yy, Z, 50, cmap=cm, alpha=.8)
    plt.colorbar(cf, ax=ax)
    #plt.colorbar(Z,ax=ax)

    # Plot also the training points
    ax.scatter(X_train[:, 0],
               X_train[:, 1],
               c=y_train,
               cmap=cm_bright,
               edgecolors='k',
               s=100)
    if activation == 'tanh':
        CT = 0
    elif activation == 'sigmoid':
        CT = 0.5
    elif activation == 'relu':
        CT = 0.011
    for num, model_val in enumerate(model_vals):
        Z_th = list()
        Zaux = model_val.predict(np.c_[xx.ravel(), yy.ravel()])
        for idx in range(Zaux.shape[1]):
            Z_th.append(Zaux[:, idx].reshape(xx.shape))
        for z_th in Z_th:
            boundary_line = np.where(np.abs(z_th - CT) < 0.01)
            ax.scatter(x_domain[boundary_line[1]],
                       y_domain[boundary_line[0]],
                       color=colors[num],
                       alpha=0.5,
                       s=10)
    boundary_line = np.where(np.abs(Z - 0.5) < 0.01)
    ax.scatter(x_domain[boundary_line[1]],
               y_domain[boundary_line[0]],
               color='k',
               alpha=0.5,
               s=10)
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())
    ax.text(xx.max() - .3,
            yy.min() + .3, ('%.2f' % score).lstrip('0'),
            size=40,
            horizontalalignment='right')
Exemplo n.º 12
0
class Painter:
    cmap_light = ListedColormap(
        ['#AAFFAA', '#AAAAFF', '#FFFFAA', '#AAAAAA', '#FFFFFF', '#FFAAAA'])

    def __init__(self, n_features):
        self.n_features = n_features
        self.col = int(np.ceil(np.sqrt(self.n_features / 2)))
        self.row = int(np.ceil(self.n_features / 2 / self.col))

    def beautify(self):
        import seaborn as sns
        sns.set(style="white", palette="muted", color_codes=True)

    def init_pic(self):
        self.fig, self.ax = plt.subplots(ncols=self.col,
                                         nrows=self.row,
                                         squeeze=False)

    def draw_pic(self,
                 data,
                 label,
                 predict,
                 img_save_path=None,
                 *args,
                 **kwargs):
        for i in range(0, self.n_features, 2):
            a = i // self.col
            b = i % self.col
            yield a, b, i

            x_min, x_max = data[:, i].min() - 1, data[:, i].max() + 1
            y_min, y_max = data[:, i + 1].min() - 1, data[:, i + 1].max() + 1

            xx = np.arange(x_min, x_max, 0.1)
            yy = np.arange(y_min, y_max, 0.1)
            xv, yv = np.meshgrid(xx, yy)
            zv = predict(np.c_[xv.ravel(), yv.ravel()])
            zv = zv.reshape(xv.shape)

            self.ax[a][b].pcolormesh(xv, yv, zv, cmap=self.cmap_light)
            self.ax[a][b].scatter(data[:, i], data[:, i + 1], c=label)

        if img_save_path:
            self.fig.savefig(img_save_path)

    def show_pic(self,
                 data,
                 label,
                 predict,
                 img_save_path=None,
                 *args,
                 **kwargs):
        for a, b, i in self.draw_pic(data, label, predict, img_save_path,
                                     *args, **kwargs):
            pass

    def init_ani(self):
        self.ani_fig, self.ani_ax = plt.subplots(ncols=self.col,
                                                 nrows=self.row,
                                                 squeeze=False)
        self.ani_fig.set_tight_layout(True)
        self.ims = []

    def img_collections(self, data, label, w, bias, *args, **kwargs):
        for a, b, i, im in self.draw_ani(data, label, w, bias, *args,
                                         **kwargs):
            pass

    def draw_ani(self, data, label, w, bias, *args, **kwargs):
        im = []
        for i in range(self.n_features // 2):
            a = i // self.col
            b = i % self.col
            yield a, b, i, im

            x_min, x_max = data[:, i].min() - 1, data[:, i].max() + 1
            y_min, y_max = data[:, i + 1].min() - 1, data[:, i + 1].max() + 1

            self.ani_ax[a][b].set_xlim(x_min, x_max)
            self.ani_ax[a][b].set_ylim(y_min, y_max)

            xx = np.arange(x_min, x_max)
            y = -(w[0] * xx + bias) / w[1]

            line, = self.ani_ax[a][b].plot(xx, y, c='black', animated=True)
            im.append(line)
            im.append(self.ani_ax[a][b].scatter(data[:, i],
                                                data[:, i + 1],
                                                c=label,
                                                animated=True))

        self.ims.append(im)

    def show_ani(self, img_save_path=None, fps=10):
        ani = animation.ArtistAnimation(self.ani_fig,
                                        self.ims,
                                        interval=1000 // len(self.ims),
                                        blit=True,
                                        repeat_delay=1000,
                                        repeat=False)

        if img_save_path is not None:
            if img_save_path.endswith('.gif'):
                from matplotlib.animation import ImageMagickWriter as Writer
                ani.save(img_save_path, writer=Writer())
            else:
                from matplotlib.animation import FFMpegWriter as Writer
                ani.save(img_save_path, writer=Writer(fps=fps))

    def show(self):
        plt.show()
Exemplo n.º 13
0
print(clusters)

# The above numbers show the two points (x and y of both) of the two cluster centers.
#

# Now we will try to define some colors and print the clustering - for k = 2

# In[5]:

# need a new import
from matplotlib.colors import ListedColormap

# we define color lists to use with K values from 2 till 5
# the color values are simply RGB values, so the colormap for k = 2, will give red ($FF0000) and green ($00FF00) colors
cmap_bold = [
    ListedColormap(['#FF0000', '#00FF00']),
    ListedColormap(['#FF0000', '#00FF00', '#0000FF']),
    ListedColormap(['#FF0000', '#00FF00', '#0000FF', '#FFFF00']),
    ListedColormap(['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF'])
]

# now plot the same points, but this time assigning the colors to indicate the clusters

plt.scatter(X[:, 0],
            X[:, 1],
            c=labels,
            edgecolor='black',
            cmap=cmap_bold[0],
            s=20)

# The important thing is that we could now <b> predict <b> which cluster a new point should belong to.
Exemplo n.º 14
0
def eda_draw(*argv):
    bw = np.zeros((256, 4))
    v = 0.9 * (256 - np.linspace(0, 255, 256)) / 255
    bw[:, 0] = v
    bw[:, 1] = v
    bw[:, 2] = v
    bw[:, 3] = np.ones(256)
    bwcmap = ListedColormap(bw)
    # size of plot
    W = 24
    H = 6
    fig1 = plt.figure(1)
    # figsize width and height in inches
    fig1.set_size_inches(W, H)
    ax1 = plt.subplot(1, 1, 1)
    plt.axis([0, W, -H / 2, H / 2])
    plt.axis('off')
    LM = W / 6
    # matrix width and heoght
    LV = W / 40
    # vector width
    FS = 0.12
    # character width
    TO = 0.4
    # title vertical offset
    SP = 0.2
    # space between objects
    LS = 0.2
    # leading space
    p = LS
    # starting x-position
    istitle = 0
    # flags presence of a title
    for a in argv:
        if isinstance(a, np.ndarray):
            sh = np.shape(a)
            if len(sh) == 1:  # conversion to nx1 array
                n = sh[0]
                m = 1
                ap = a
                a = np.zeros((n, 1))
                a[:, 0] = ap
            else:
                n = sh[0]
                m = sh[1]
            if m == 1:
                pold = p
                left = p
                right = p + LV
                bottom = -LM / 2
                top = LM / 2
                plt.imshow(a,
                           cmap=bwcmap,
                           vmin=np.min(a),
                           vmax=np.max(a),
                           extent=(left, right, bottom, top))
                p = p + LV
                pm = (p + pold) / 2
                if istitle:
                    plt.text(pm,
                             -(LM / 2) - TO,
                             titlestr,
                             horizontalalignment='center')
                    istitle = 0
                p = p + SP
            else:
                pold = p
                left = p
                right = p + LM
                bottom = -LM / 2
                top = LM / 2
                plt.imshow(a,
                           cmap=bwcmap,
                           vmin=np.min(a),
                           vmax=np.max(a),
                           extent=(left, right, bottom, top))
                p = p + LM
                pm = (p + pold) / 2
                if istitle:
                    plt.text(pm,
                             -(LM / 2) - TO,
                             titlestr,
                             horizontalalignment='center')
                    istitle = 0
                p = p + SP
        elif isinstance(a, str):
            ns = len(a)
            istitle = 0
            if (ns >= 6):
                if 'title ' in a[0:6]:
                    istitle = 1
                    titlestr = a[6:]
            if (istitle != 1):
                plt.text(p, 0, a)
                p = p + ns * FS + SP
    #plt.show();
    return 1
Exemplo n.º 15
0
X_set, y_set = X_train, y_train

fig = plt.figure(figsize=(16, 8))
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())

for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[(y_set == j).ravel(), 0],
                X_set[(y_set == j).ravel(), 1],
                c=np.array([ListedColormap(('red', 'green'))(i)]),
                label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
# plt.show()
plt.savefig('../img/logistic_regression_train.png')
    vth = params.Va + params.Ka*nu0_prediction(start, length) - params.Ka*log(length*ra*params.gna_dens*length*pi*params.axon_diam*(params.ENa-params.Va)/params.Ka)
    return vth

thresholds_pred = zeros((m,m))
for i in range(m):
    for j in range(m):
        thresholds_pred[i,j] = V0_prediction(starts[i], lengths[j]) * 1e3

### Plots
        
# Custom colormap
top = get_cmap('Oranges_r', 128)
bottom = get_cmap('Blues', 128)
newcolors = vstack((top(linspace(0.5, 1, 128)),
                       bottom(linspace(0.5, 1, 128))))
newcmp = ListedColormap(newcolors, name='OrangeBlue')
cmap = plt.get_cmap(newcmp)
colors = [cmap(i) for i in np.linspace(0, 1, m)]

# Figure
lengths_range_label = lengths/um
starts_range_label = starts/um

fig_pred = figure(3, figsize=(6,5))

# Panel A: BIO model: threshold vs AIS start position, for different AIS lengths
ax1 = fig_pred.add_subplot(221)
ax1.text(26.5, -42,'Biophysical model', fontsize=12)
for k in range(m):
    plot(starts/um, thresholds[:,k], color=colors[k]) 
ax1.set_ylabel('$V_s$ (mV)')
Exemplo n.º 17
0
if year==2001:
        landuse_map_in = np.load(default_directory + "/data/finalData/npy/landuse_2001.npy")
        from calculate_objectives_2001 import calculate_tot_profit2001 as calculate_tot_profit
        from calculate_objectives_2001 import calculate_area2001 as calculate_area
elif year == 2016:
        landuse_map_in = np.load(default_directory + "/data/finalData/npy/landuse_2016.npy")
        from calculate_objectives_2016 import calculate_tot_profit2016 as calculate_tot_profit
        from calculate_objectives_2016 import calculate_area2016 as calculate_area
else:
        raise ValueError("Year must be 2001 or 2016")


f2, ax2 = plt.subplots(1)
cmap2 = ListedColormap(["#10773e","#b3cc33", "#0cf8c1", "#a4507d",
 "#877712","#be94e8","#eeefce","#1b5ee4",
"#614040","#00000000"])
legend_landuse2 = [mpatches.Patch(color="#10773e",label = 'Forest'),
 mpatches.Patch(color="#b3cc33",label = 'Cerrado'),
 mpatches.Patch(color="#0cf8c1",label = 'Secondary vegetation'),
 mpatches.Patch(color="#a4507d",label = 'Soy'),
 mpatches.Patch(color="#877712",label = 'Sugarcane'),
 mpatches.Patch(color="#be94e8",label = 'Fallow/cotton'),
 mpatches.Patch(color="#eeefce",label = 'Pasture'),
 mpatches.Patch(color="#1b5ee4",label = 'Water'),
 mpatches.Patch(color="#614040",label = 'Urban'),
 mpatches.Patch(color="#00000000",label = 'No data')]
im1= plt.imshow(landuse_map_in,interpolation='none',
 cmap=cmap2,vmin = 0.5, vmax = 10.5)
ax2.set_title('Landuse map reclassed')
ax2.set_xlabel('Column #')
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
from sklearn.inspection import DecisionBoundaryDisplay

n_neighbors = 15

# import some data to play with
iris = datasets.load_iris()

# we only take the first two features. We could avoid this ugly
# slicing by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target

# Create color maps
cmap_light = ListedColormap(["orange", "cyan", "cornflowerblue"])
cmap_bold = ["darkorange", "c", "darkblue"]

for weights in ["uniform", "distance"]:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X, y)

    _, ax = plt.subplots()
    DecisionBoundaryDisplay.from_estimator(
        clf,
        X,
        cmap=cmap_light,
        ax=ax,
        response_method="predict",
        plot_method="pcolormesh",
Exemplo n.º 19
0
def pca_plot(X, estimator, y=None, cmap=None, figsize=(10, 8),
             title='Principal Components Analysis', title_font_size=14,
             show=True, ax=None, **kwargs):
    """Function to plot a PCA analysis of 1, 2, or 3 dims.

    Parameters
    ----------
    X : array-like of shape = [n_samples, n_features]
        matrix to perform PCA analysis on.

    estimator : instance
        PCA estimator. Assumes a Scikit-learn API.

    y : array-like of shape = [n_samples, ] or None (default = None)
        training labels to be used for color highlighting.

    cmap : object, optional
        cmap object to pass to :obj:`matplotlib.pyplot.scatter`.

    figsize : tuple (default = (10, 8))
        Size of figure.

    title : str
        figure title if shown.

    title_font_size : int
        title font size.

    show : bool (default = True)
        whether to print figure :obj:`matplotlib.pyplot.show`.

    ax : object, optional
        axis to attach plot to.

    **kwargs : optional
        arguments to pass to :obj:`matplotlib.pyplot.scatter`.

    Returns
    -------
    ax : optional
        if ``ax`` was specified, returns ``ax`` with plot attached.
    """
    Z = X.values if isinstance(X, (DataFrame, Series)) else X

    Z = estimator.fit_transform(Z)

    # prep figure if no axis supplied
    if ax is None:
        f, ax = plt.subplots(figsize=figsize)
        if estimator.n_components == 3:
            ax = f.add_subplot(111, projection='3d')

    if cmap is None:
        cmap = ListedColormap(color_palette('husl'))

    if estimator.n_components == 1:
        ax.scatter(Z, c=y, cmap=cmap, **kwargs)
    elif estimator.n_components == 2:
        ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap=cmap, **kwargs)
    elif estimator.n_components == 3:
        ax.scatter(Z[:, 0], Z[:, 1], Z[:, 2], c=y, cmap=cmap, **kwargs)
    else:
        raise ValueError("'n_components' is too large to visualize. "
                         "Set to one of [1, 2, 3].")

    if show:
        plt.title(title, fontsize=title_font_size)
        plt.show()

    return ax
Exemplo n.º 20
0
                #catch disk full
                print('error: ',e)
                break
            lst=[]
        lst.append(line)
        i+=1

train = pd.read_hdf('file.h5',key='train')
#combine with categries
train = pd.merge(categories,train,right_on='category_id',left_index=True)

train.info()

cats = train['category_level1'].value_counts()
cats.head()

abbriv = cats.index.str.split('\W').str[0].str.strip()

sns.set_style('white')
fig,ax = plt.subplots(1,figsize=(12,6))
pal = ListedColormap(sns.color_palette('Paired').as_hex())
colors = pal(np.interp(cats,[cats.min(),cats.max()],[0,1]))
bars = ax.bar(range(1,len(cats)+1),cats,color=colors);
ax.set_xticks([]);
ax.set_xlim(0,len(cats))
ax1 = plt.twiny(ax)
ax1.set_xlim(0,len(cats))
ax1.set_xticks(range(1,len(abbriv)+1,1));
ax1.set_xticklabels(abbriv.values,rotation=90);
# sns.despine();
chance_infeccao = 1
chance_infeccao_tipo2 = 0.2
chance_morte = 0.1
atualizacoes_cura = 10
percentual_inicial_tipo1 = 0.0
percentual_inicial_tipo2 = 0.0

sim = Simulador(6, percentual_inicial_tipo1, percentual_inicial_tipo2,
                chance_infeccao, chance_infeccao_tipo2, chance_morte,
                atualizacoes_cura)

#print(sim.lista_matrizes_posicionamento[0])
#print(sim.lista_infectados_tipo_2)
#print(sim.lista_infectados_tipo_1)
cmap = ListedColormap(['w', 'y', 'r', 'blue', 'black'])

# while sim.dataframe.iloc[-1]['num_infect_t1']+sim.dataframe.iloc[-1]['num_infect_t2'] > 0:
#     sim.iterar()
#     print(sim.dataframe.iloc[-1])
#print("xxxxxxxxxxxxxxxxxTipo: ",type(sim.lista_matrizes_posicionamento[len(sim.lista_matrizes_posicionamento)-1].toarray()))
#plt.matshow(sim.lista_matrizes_posicionamento[0], cmap = cmap, vmin= 0, vmax = 4)
#plt.show()

for i in range(12):
    #plt.matshow(sim.lista_matrizes_status[i].toarray(), cmap = cmap, vmin= 0, vmax = 4)
    print(i)
    print("Status")
    print(sim.matriz_status.toarray())
    print("Cura")
    print(sim.matriz_atualizacoes_cura.toarray())
# Fitting classifier to the Training set
# Create your classifier here

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Classifier (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green')))
variance_accuracy = accuracies.std()

# visualising training set results
from matplotlib.colors import ListedColormap
X1, X2 = np.meshgrid(
    np.arange(start=X_train[:, 0].min() - 1,
              stop=X_train[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_train[:, 1].min() - 1,
              stop=X_train[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             cmap=ListedColormap(('red', 'green')),
             alpha=0.65)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_train)):
    plt.scatter(X_train[y_train == j, 0],
                X_train[y_train == j, 1],
                c=ListedColormap(('blue', 'pink'))(i),
                label=j)
plt.title('Kernel SVM - Training Set')
plt.legend()
plt.xlabel('Age')
plt.ylabel('Salary')
plt.show()

# visualising test set results
Exemplo n.º 24
0
def plot_2d_scatter(X, y, colors=['blue', 'red']):
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=ListedColormap(colors))
    plt.show()
Exemplo n.º 25
0
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol,
                borderstyle, borderwidth, alpha, **options):
    r"""
    ``region_plot`` takes a boolean function of two variables, `f(x,y)`
    and plots the region where f is True over the specified
    ``xrange`` and ``yrange`` as demonstrated below.

    ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)``

    INPUT:

    - ``f`` -- a boolean function or a list of boolean functions of two variables

    - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple
      ``(x,xmin,xmax)``

    - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple
      ``(y,ymin,ymax)``

    - ``plot_points``  -- integer (default: 100); number of points to plot
      in each direction of the grid

    - ``incol`` -- a color (default: ``'blue'``), the color inside the region

    - ``outcol`` -- a color (default: ``None``), the color of the outside
      of the region

    If any of these options are specified, the border will be shown as indicated,
    otherwise it is only implicit (with color ``incol``) as the border of the
    inside of the region.

     - ``bordercol`` -- a color (default: ``None``), the color of the border
       (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``)

    - ``borderstyle``  -- string (default: 'solid'), one of ``'solid'``,
      ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``,
      ``'--'``, ``':'``, ``'-.'``.

    - ``borderwidth``  -- integer (default: None), the width of the border in pixels

    - ``alpha`` -- (default: 1) How transparent the fill is. A number between 0 and 1.

    - ``legend_label`` -- the label for this item in the legend

    - ``base`` - (default: 10) the base of the logarithm if
      a logarithmic scale is set. This must be greater than 1. The base
      can be also given as a list or tuple ``(basex, basey)``.
      ``basex`` sets the base of the logarithm along the horizontal
      axis and ``basey`` sets the base along the vertical axis.

    - ``scale`` -- (default: ``"linear"``) string. The scale of the axes.
      Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``,
      ``"semilogy"``.

      The scale can be also be given as single argument that is a list
      or tuple ``(scale, base)`` or ``(scale, basex, basey)``.

      The ``"loglog"`` scale sets both the horizontal and vertical axes to
      logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis
      to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis
      to logarithmic scale. The ``"linear"`` scale is the default value
      when :class:`~sage.plot.graphics.Graphics` is initialized.


    EXAMPLES:

    Here we plot a simple function of two variables::

        sage: x,y = var('x,y')
        sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3))
        Graphics object consisting of 1 graphics primitive

    Here we play with the colors::

        sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray')
        Graphics object consisting of 2 graphics primitives

    An even more complicated plot, with dashed borders::

        sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250)
        Graphics object consisting of 2 graphics primitives

    A disk centered at the origin::

        sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1))
        Graphics object consisting of 1 graphics primitive

    A plot with more than one condition (all conditions must be true for the statement to be true)::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2))
        Graphics object consisting of 1 graphics primitive

    Since it doesn't look very good, let's increase ``plot_points``::

        sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    To get plots where only one condition needs to be true, use a function.
    Using lambda functions, we definitely need the extra ``plot_points``::

        sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400)
        Graphics object consisting of 1 graphics primitive

    The first quadrant of the unit circle::

        sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400)
        Graphics object consisting of 1 graphics primitive

    Here is another plot, with a huge border::

        sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50)
        Graphics object consisting of 2 graphics primitives

    If we want to keep only the region where x is positive::

        sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50)
        Graphics object consisting of 1 graphics primitive

    Here we have a cut circle::

        sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200)
        Graphics object consisting of 2 graphics primitives

    The first variable range corresponds to the horizontal axis and
    the second variable range corresponds to the vertical axis::

        sage: s,t=var('s,t')
        sage: region_plot(s>0,(t,-2,2),(s,-2,2))
        Graphics object consisting of 1 graphics primitive

    ::

        sage: region_plot(s>0,(s,-2,2),(t,-2,2))
        Graphics object consisting of 1 graphics primitive

    An example of a region plot in 'loglog' scale::

        sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog')
        Graphics object consisting of 1 graphics primitive

    TESTS:

    To check that :trac:`16907` is fixed::

        sage: x, y = var('x, y')
        sage: disc1 = region_plot(x^2+y^2 < 1, (x, -1, 1), (y, -1, 1), alpha=0.5)
        sage: disc2 = region_plot((x-0.7)^2+(y-0.7)^2 < 0.5, (x, -2, 2), (y, -2, 2), incol='red', alpha=0.5)
        sage: disc1 + disc2
        Graphics object consisting of 2 graphics primitives

    To check that :trac:`18286` is fixed::
        sage: x, y = var('x, y')
        sage: region_plot([x == 0], (x, -1, 1), (y, -1, 1))
        Graphics object consisting of 1 graphics primitive
        sage: region_plot([x^2+y^2==1, x<y], (x, -1, 1), (y, -1, 1))
        Graphics object consisting of 1 graphics primitive

    """

    from sage.plot.all import Graphics
    from sage.plot.misc import setup_for_eval_on_grid
    from sage.symbolic.expression import is_Expression
    from warnings import warn
    import numpy

    if not isinstance(f, (list, tuple)):
        f = [f]

    feqs = [
        equify(g) for g in f if is_Expression(g)
        and g.operator() is operator.eq and not equify(g).is_zero()
    ]
    f = [
        equify(g) for g in f
        if not (is_Expression(g) and g.operator() is operator.eq)
    ]
    neqs = len(feqs)
    if neqs > 1:
        warn(
            "There are at least 2 equations; If the region is degenerated to points, plotting might show nothing."
        )
        feqs = [sum([fn**2 for fn in feqs])]
        neqs = 1
    if neqs and not bordercol:
        bordercol = incol
    if not f:
        return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, fill=False, \
                             linewidth=borderwidth, linestyle=borderstyle, color=bordercol, **options)
    f_all, ranges = setup_for_eval_on_grid(feqs + f, [xrange, yrange],
                                           plot_points)
    xrange, yrange = [r[:2] for r in ranges]

    xy_data_arrays = numpy.asarray(
        [[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)]
          for y in xsrange(*ranges[1], include_endpoint=True)]
         for func in f_all[neqs::]],
        dtype=float)
    xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0))
    # Now we need to set entries to negative iff all
    # functions were negative at that point.
    neg_indices = (xy_data_arrays < 0).all(axis=0)
    xy_data_array[neg_indices] = -xy_data_array[neg_indices]

    from matplotlib.colors import ListedColormap
    incol = rgbcolor(incol)
    if outcol:
        outcol = rgbcolor(outcol)
        cmap = ListedColormap([incol, outcol])
        cmap.set_over(outcol, alpha=alpha)
    else:
        outcol = rgbcolor('white')
        cmap = ListedColormap([incol, outcol])
        cmap.set_over(outcol, alpha=0)
    cmap.set_under(incol, alpha=alpha)

    g = Graphics()

    # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'.
    # Otherwise matplotlib complains.
    scale = options.get('scale', None)
    if isinstance(scale, (list, tuple)):
        scale = scale[0]
    if scale == 'semilogy' or scale == 'semilogx':
        options['aspect_ratio'] = 'automatic'

    g._set_extra_kwds(
        Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax']))

    if neqs == 0:
        g.add_primitive(
            ContourPlot(
                xy_data_array, xrange, yrange,
                dict(contours=[-1e-20, 0, 1e-20],
                     cmap=cmap,
                     fill=True,
                     **options)))
    else:
        mask = numpy.asarray([[elt > 0 for elt in rows]
                              for rows in xy_data_array],
                             dtype=bool)
        xy_data_array = numpy.asarray([[
            f_all[0](x, y) for x in xsrange(*ranges[0], include_endpoint=True)
        ] for y in xsrange(*ranges[1], include_endpoint=True)],
                                      dtype=float)
        xy_data_array[mask] = None
    if bordercol or borderstyle or borderwidth:
        cmap = [rgbcolor(bordercol)] if bordercol else ['black']
        linestyles = [borderstyle] if borderstyle else None
        linewidths = [borderwidth] if borderwidth else None
        g.add_primitive(
            ContourPlot(
                xy_data_array, xrange, yrange,
                dict(linestyles=linestyles,
                     linewidths=linewidths,
                     contours=[0],
                     cmap=[bordercol],
                     fill=False,
                     **options)))

    return g
Exemplo n.º 26
0
def yearplot(data, year=None, how='sum', vmin=None, vmax=None, cmap='Reds',
             fillcolor='whitesmoke', linewidth=1, linecolor=None,
             daylabels=calendar.day_abbr[:], dayticks=True,
             monthlabels=calendar.month_abbr[1:], monthticks=True,
             monthseparator=False, separatorwidth=3, separatorcolor='black',
             colorbar=False, colorbar_kws=None, ax=None, **kwargs):
    """
    Plot one year from a timeseries as a calendar heatmap.

    Parameters
    ----------
    data : Series
        Data for the plot. Must be indexed by a DatetimeIndex.
    year : integer
        Only data indexed by this year will be plotted. If `None`, the first
        year for which there is data will be plotted.
    how : string
        Method for resampling data by day. If `None`, assume data is already
        sampled by day and don't resample. Otherwise, this is passed to Pandas
        `Series.resample`.
    vmin, vmax : floats
        Values to anchor the colormap. If `None`, min and max are used after
        resampling data by day.
    cmap : matplotlib colormap name or object
        The mapping from data values to color space.
    fillcolor : matplotlib color
        Color to use for days without data.
    linewidth : float
        Width of the lines that will divide each day.
    linecolor : color
        Color of the lines that will divide each day. If `None`, the axes
        background color is used, or 'white' if it is transparent.
    daylabels : list
        Strings to use as labels for days, must be of length 7.
    dayticks : list or int or bool
        If `True`, label all days. If `False`, don't label days. If a list,
        only label days with these indices. If an integer, label every n day.
    monthlabels : list
        Strings to use as labels for months, must be of length 12.
    monthticks : list or int or bool
        If `True`, label all months. If `False`, don't label months. If a
        list, only label months with these indices. If an integer, label every
        n month.
    monthseparator : bool
        If `True`, adds line between months.
    separatorwidth : float
        Width of the month separators.
    separatorcolor : string
        Color of the month separators.
    ax : matplotlib Axes
        Axes in which to draw the plot, otherwise use the currently-active
        Axes.
    kwargs : other keyword arguments
        All other keyword arguments are passed to matplotlib `ax.pcolormesh`.

    Returns
    -------
    ax : matplotlib Axes
        Axes object with the calendar heatmap.

    Examples
    --------

    By default, `yearplot` plots the first year and sums the values per day:

    .. plot::
        :context: close-figs

        calmap.yearplot(events)

    We can choose which year is plotted with the `year` keyword argment:

    .. plot::
        :context: close-figs

        calmap.yearplot(events, year=2015)

    The appearance can be changed by using another colormap. Here we also use
    a darker fill color for days without data and remove the lines:

    .. plot::
        :context: close-figs

        calmap.yearplot(events, cmap='YlGn', fillcolor='grey',
                        linewidth=0)

    The axis tick labels can look a bit crowded. We can ask to draw only every
    nth label, or explicitely supply the label indices. The labels themselves
    can also be customized:

    .. plot::
        :context: close-figs

        calmap.yearplot(events, monthticks=3, daylabels='MTWTFSS',
                        dayticks=[0, 2, 4, 6])

    """
    colorbar_kws = colorbar_kws or {'orientation': 'horizontal'}
    if year is None:
        year = data.index.sort_values()[0].year

    if how is None:
        # Assume already sampled by day.
        by_day = data
    else:
        # Sample by day.
        if _pandas_18:
            by_day = data.resample('D').agg(how)
        else:
            by_day = data.resample('D', how=how)

    # Min and max per day.
    if vmin is None:
        vmin = by_day.min()
    if vmax is None:
        vmax = by_day.max()

    if ax is None:
        ax = plt.gca()

    if linecolor is None:
        # Unfortunately, linecolor cannot be transparent, as it is drawn on
        # top of the heatmap cells. Therefore it is only possible to mimic
        # transparent lines by setting them to the axes background color. This
        # of course won't work when the axes itself has a transparent
        # background so in that case we default to white which will usually be
        # the figure or canvas background color.
        linecolor = ax.get_facecolor()
        if ColorConverter().to_rgba(linecolor)[-1] == 0:
            linecolor = 'white'

    # Filter on year.
    by_day = by_day[str(year)]

    # Add missing days.
    by_day = by_day.reindex(
        pd.date_range(start=str(year), end=str(year + 1),
                      freq='D', tz=by_day.index.tzinfo)[:-1])

    # Create data frame we can pivot later.
    by_day = pd.DataFrame({'data': by_day,
                           'fill': 1,
                           'day': by_day.index.dayofweek,
                           'week': by_day.index.week,
                           'month': by_day.index.month})

    # There may be some days assigned to previous year's last week or
    # next year's first week. We create new week numbers for them so
    # the ordering stays intact and week/day pairs unique.
    if by_day.loc[(by_day.index.month == 1), 'week'].max() > 50:
        by_day.loc[(by_day.index.month == 1) & (by_day.week > 50), 'week'] = 0
        by_day.week = by_day.week + 1
    by_day.loc[(by_day.index.month == 12) & (by_day.week < 10), 'week'] \
        = by_day.week.max() + 1


    # Pivot data on day and week and mask NaN days.
    plot_data = by_day.pivot('day', 'week', 'data').values[::-1]
    plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data)

    # Do the same for all days of the year, not just those we have data for.
    fill_data = by_day.pivot('day', 'week', 'fill').values[::-1]
    fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data)

    # Draw heatmap for all days of the year with fill color.
    ax.pcolormesh(fill_data, vmin=0, vmax=1, cmap=ListedColormap([fillcolor]))

    # Draw heatmap.
    kwargs['linewidth'] = linewidth
    kwargs['edgecolors'] = linecolor
    mappable = ax.pcolormesh(plot_data, vmin=vmin, vmax=vmax, cmap=cmap, **kwargs)

    # Limit heatmap to our data. Add a little room for the outside lines (purely esthetic)
    ax.set(xlim=(-0.3, plot_data.shape[1] + 0.3), ylim=(-0.3, plot_data.shape[0] + 0.3))

    # Draw lines at the start of each month
    if monthseparator:
        linekwargs = {'c': separatorcolor, 'lw': separatorwidth, 'ls': '-'}
        for key, fd in by_day.groupby('month').first().iterrows():
            if key == 1:
                continue
            x = [fd.week - 1, fd.week - 1]
            y = [0, 7 - fd.day]

            # Make sure we don't get a "hat" on months that start on Monday
            if fd.day != 0:
                x.extend([fd.week, fd.week])
                y.extend([7 - fd.day, 7])
            
            ax.plot(x, y, **linekwargs)

    # Square cells.
    ax.set_aspect('equal')

    # Remove spines and ticks.
    for side in ('top', 'right', 'left', 'bottom'):
        ax.spines[side].set_visible(False)
    ax.xaxis.set_tick_params(which='both', length=0)
    ax.yaxis.set_tick_params(which='both', length=0)

    # Get indices for monthlabels.
    if monthticks is True:
        monthticks = range(len(monthlabels))
    elif monthticks is False:
        monthticks = []
    elif isinstance(monthticks, int):
        monthticks = range(len(monthlabels))[monthticks // 2::monthticks]

    # Get indices for daylabels.
    if dayticks is True:
        dayticks = range(len(daylabels))
    elif dayticks is False:
        dayticks = []
    elif isinstance(dayticks, int):
        dayticks = range(len(daylabels))[dayticks // 2::dayticks]

    ax.set_xlabel('')
    ax.set_xticks(by_day.groupby('month')['week'].mean().values - 0.5)
    ax.set_xticklabels([monthlabels[i] for i in monthticks], ha='center')

    ax.set_ylabel('')
    ax.yaxis.set_ticks_position('right')
    ax.set_yticks([6 - i + 0.5 for i in dayticks])
    ax.set_yticklabels([daylabels[i] for i in dayticks], rotation='horizontal',
                       va='center')

    if colorbar:
        ax.get_figure().colorbar(mappable, **colorbar_kws)

    return ax
Exemplo n.º 27
0
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0],
                X_set[y_set == j, 1],
                c=ListedColormap(('red', 'green'))(i),
                label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
x=sc.fit_transform(x)

from sklearn.cross_validation import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=1/4,random_state=0)

from sklearn.svm import SVC
clf=SVC(kernel='rbf',random_state=0)
clf.fit(x_train,y_train)
y_predict=clf.predict(x_test)

from sklearn.metrics import confusion_matrix,accuracy_score
cm=confusion_matrix(y_test,y_predict)
ascore=accuracy_score(y_test,y_predict)

from matplotlib.colors import ListedColormap
x_set,y_set=x_train,y_train
X,Y=np.meshgrid(np.arange(x_set[:,0].min() - 1,x_set[:,0].max() + 1,0.01),
                np.arange(x_set[:,1].min() - 1,x_set[:,1].max() + 1,0.01))
plt.contourf(X,Y,clf.predict(np.array([X.ravel(),Y.ravel()]).T).reshape(X.shape),
             alpha=0.5,cmap=ListedColormap(('red','green')))
plt.scatter(x_set[y_set==0,0],x_set[y_set==0,1],color='red')
plt.scatter(x_set[y_set==1,0],x_set[y_set==1,1],color='green')

from matplotlib.colors import ListedColormap
x_set,y_set=x_test,y_test
X,Y=np.meshgrid(np.arange(x_set[:,0].min() - 1,x_set[:,0].max() + 1,0.01),
                np.arange(x_set[:,1].min() - 1,x_set[:,1].max() + 1,0.01))
plt.contourf(X,Y,clf.predict(np.array([X.ravel(),Y.ravel()]).T).reshape(X.shape),
             alpha=0.5,cmap=ListedColormap(('red','green')))
plt.scatter(x_set[y_set==0,0],x_set[y_set==0,1],color='red')
plt.scatter(x_set[y_set==1,0],x_set[y_set==1,1],color='green')
Exemplo n.º 29
0
from matplotlib.colors import ListedColormap

X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0],
                X_set[y_set == j, 1],
                c=ListedColormap(('red', 'green'))(i),
                label=j)
plt.title('KNN Classifier (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
Exemplo n.º 30
0
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import tree
import collections
import seaborn as sns
import numpy as np
import pandas as pd
from matplotlib.colors import ListedColormap, to_hex

colors = ['xkcd:sky', 'xkcd:grass']
cmap = ListedColormap(colors)


def set_plot_style():
    sns.reset_orig()
    plt.rcParams["figure.figsize"] = (9.23, 9.23 / 3 * 2)
    plt.rcParams["figure.dpi"] = 100
    plt.rcParams["font.size"] = 14
    plt.rcParams["lines.linewidth"] = 2
    plt.rcParams["axes.spines.top"] = False
    plt.rcParams["axes.spines.right"] = False


def twospirals(n_samples, noise=0.5):
    """
     Returns the two spirals dataset.
    """
    n = np.sqrt(np.random.rand(n_samples, 1)) * 360 * (2 * np.pi) / 360
    d1x = -np.cos(n) * n + np.random.rand(n_samples, 1) * noise
    d1y = np.sin(n) * n + np.random.rand(n_samples, 1) * noise