Пример #1
0
def show_clusters_over_time(task_output_path=None,
                            query_laps=[0, 1, 2, 5, 10, None],
                            nrows=2):

    ncols = int(np.ceil(len(query_laps) // float(nrows)))
    fig_handle, ax_handle_list = pylab.subplots(figsize=(FIG_SIZE[0] * ncols,
                                                         FIG_SIZE[1] * nrows),
                                                nrows=nrows,
                                                ncols=ncols,
                                                sharex=True,
                                                sharey=True)
    for plot_id, lap_val in enumerate(query_laps):
        cur_model, lap_val = bnpy.load_model_at_lap(task_output_path, lap_val)
        # Plot the current model
        cur_ax_handle = ax_handle_list.flatten()[plot_id]
        bnpy.viz.PlotComps.plotCompsFromHModel(
            cur_model,
            Data=dataset,
        )  #ax_handle=cur_ax_handle)
        cur_ax_handle.set_xticks([-2, -1, 0, 1, 2])
        cur_ax_handle.set_yticks([-2, -1, 0, 1, 2])
        cur_ax_handle.set_xlabel("lap: %d" % lap_val)
    pylab.tight_layout()
    pylab.savefig("results/covMat1.png")
    pylab.waitforbuttonpress()
    pylab.show()
def augmentation_demo(filename, it=20, mean_RGB=None):
    """
    Little demo to show how data augmentation is performed on a single image.

    Parameters
    ----------
    filename : str
        Path of the image
    it : int
        Number of examples of data augmentation

    """
    if mean_RGB is None:
        mean_RGB = np.array([107.59348955,  112.1047813,   80.9982362])
    else:
        mean_RGB = np.array(mean_RGB)
    batch = data_augmentation([filename]*it, mean_RGB=mean_RGB)

    plt.ion()
    fig, [ax1, ax2] = plt.subplots(1, 2, num=1)
    ax1.set_title('Original image')
    ax2.set_title('Transformed image')
    image = Image.open(filename)
    ax1.imshow(np.asarray(image))

    mean_RGB = mean_RGB.astype(np.float32)
    for im in batch:
        im = im[::-1, :, :]
        im = np.transpose(im, (1, 2, 0))
        im = im + mean_RGB[None, None, :]
        ax2.imshow(im.astype(np.uint8))
        plt.waitforbuttonpress(1)
Пример #3
0
 def plot(s):
   s.plot(style='k--')
   s=pd.rolling_mean(s, 20, min_periods=1)
   s.plot()
   m=extremeOf(s)
   m.plot(style='ro')
   plt.waitforbuttonpress()
   plt.close('all')
Пример #4
0
def plot_boundary(X, Y, model, title=''):
    """

    Represents the boundaries of a generic learning model over data

    :param X: np.array
        Data points. Shape = (num_samples, dim)
    :param Y: np.array
        Groundtruth labels. (Shape = (num_samples,)
    :param model: SVC
        A sklearn.SVC fit model
    :param title:  str
        An optional title for the plot
    """

    # Initialize subplots
    fig, ax = plt.subplots(1, 2)
    ax[0].scatter(X[:, 0],
                  X[:, 1],
                  c=Y,
                  s=40,
                  zorder=10,
                  cmap=cmap,
                  edgecolors='k')

    # Evaluate limits
    x_min = np.min(X[:, 0])
    x_max = np.max(X[:, 0])
    y_min = np.min(X[:, 1])
    y_max = np.max(X[:, 1])

    # Predict all over a grid
    XX, YY = np.mgrid[x_min:x_max:500j, y_min:y_max:500j]
    Z = model.predict(np.c_[XX.ravel(), YY.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(XX.shape)
    ax[1].pcolormesh(XX, YY, Z, cmap=plt.cm.Paired)
    ax[1].scatter(X[:, 0],
                  X[:, 1],
                  c=Y,
                  s=40,
                  zorder=10,
                  cmap=cmap,
                  edgecolors='k')

    # Set Stuff for subplots
    for s in [0, 1]:
        ax[s].set_xlim([x_min, x_max])
        ax[s].set_ylim([y_min, y_max])
        ax[s].set_xticks([])
        ax[s].set_yticks([])

    ax[0].set_title('Data')
    ax[1].set_title('Boundary')

    plt.waitforbuttonpress()
Пример #5
0
def main():
    random_start = 1
    do_pause = 1
    if random_start:
        teams1 = np.random.random((DIMENSION, DIMENSION))
        teams1 = teams1 / teams1.sum()
        teams2 = np.random.random((DIMENSION, DIMENSION))
        teams2 = teams2 / teams2.sum()
    else:
        teams1 = [STARTING_PCT] * DIMENSION**2
        teams1 = np.reshape(teams1, (DIMENSION, DIMENSION))
        teams2 = [STARTING_PCT] * DIMENSION**2
        teams2 = np.reshape(teams2, (DIMENSION, DIMENSION))
    fig, axarr = plot_init(np.matrix(teams1), np.matrix(teams2))
    for k in range(rounds):
        print "round:", k
        teams1, teams2 = update(teams1, teams2, k)
        if k % 15 == 0 and do_pause: plt.waitforbuttonpress()
        plot_update(fig, axarr, teams1, teams2, k)

    pause = raw_input("press enter to exit")
Пример #6
0
def main():
    random_start = 1
    do_pause = 1
    if random_start:
        teams1 = np.random.random((DIMENSION, DIMENSION))
        teams1 = teams1 / teams1.sum()
        teams2 = np.random.random((DIMENSION, DIMENSION))
        teams2 = teams2 / teams2.sum()
    else:
        teams1 = [STARTING_PCT] * DIMENSION ** 2
        teams1 = np.reshape(teams1, (DIMENSION, DIMENSION))
        teams2 = [STARTING_PCT] * DIMENSION ** 2
        teams2 = np.reshape(teams2, (DIMENSION, DIMENSION))
    fig, axarr = plot_init(np.matrix(teams1), np.matrix(teams2))
    for k in range(rounds):
        print "round:", k
        teams1, teams2 = update(teams1, teams2, k)
        if k % 15 == 0 and do_pause:
            plt.waitforbuttonpress()
        plot_update(fig, axarr, teams1, teams2, k)

    pause = raw_input("press enter to exit")
Пример #7
0
 def _wait_for_movement_key_press():
   """Get key press."""
   ready = False
   while not ready:
     x = plt.waitforbuttonpress(timeout=self._timeout)
     if x is None:
       logging.info('Timed out. You took longer than %d seconds to click.',
                    self._timeout)
     elif not x:
       logging.info('You clicked, but you are supposed to use the Keyboard.')
       self.help()
     elif self._movement is not None:
       ready = True
Пример #8
0
def main():
    # Whether or not to have a noisy start. This should be a proper parameter.
    random_start = 0

    # What does this do?
    do_pause=1

    if random_start:
        # Randomize strategy distribution
        teams = np.random.random((DIMENSION,DIMENSION))
        # Normalize
        teams = teams / teams.sum()   
    else:
        # Create uniform strategy distribution
        teams = [STARTING_PCT] * DIMENSION ** 2
        teams = np.reshape(teams, (DIMENSION, DIMENSION))

    # Initialize plot with initial matrix? Not 100% sure
    fig, axarr = plot_init(np.matrix(teams))

    # Main loop
    for k in range(rounds):
        # Print current round to console
        print "round:", k

        # Update strategy distribution
        teams = update(teams, k)

        # Pause if appropriate
        if k % 25 == 0 and do_pause: plt.waitforbuttonpress()

        # Update screen
        plot_update(fig ,axarr,teams,k)
    
    # Pause
    pause = raw_input("press enter to exit")
Пример #9
0
def main():
    # Whether or not to have a noisy start. This should be a proper parameter.
    random_start = 0

    # What does this do?
    do_pause = 1

    if random_start:
        # Randomize strategy distribution
        teams = np.random.random((DIMENSION, DIMENSION))
        # Normalize
        teams = teams / teams.sum()
    else:
        # Create uniform strategy distribution
        teams = [STARTING_PCT] * DIMENSION**2
        teams = np.reshape(teams, (DIMENSION, DIMENSION))

    # Initialize plot with initial matrix? Not 100% sure
    fig, axarr = plot_init(np.matrix(teams))

    # Main loop
    for k in range(rounds):
        # Print current round to console
        print "round:", k

        # Update strategy distribution
        teams = update(teams, k)

        # Pause if appropriate
        if k % 25 == 0 and do_pause: plt.waitforbuttonpress()

        # Update screen
        plot_update(fig, axarr, teams, k)

    # Pause
    pause = raw_input("press enter to exit")
Пример #10
0
 def _get_click():
   """Get mouse click."""
   while True:
     x = plt.waitforbuttonpress(timeout=self._timeout)
     if x is None:
       logging.info('Timed out. You took longer than %d seconds to click.',
                    self._timeout)
       click = None
     elif x:
       logging.info('You pressed a key, but were supposed to click with the '
                    'mouse.')
       self.help()
       click = None
     else:
       click = self._click
     return click
Пример #11
0
def main():
    # Camera parameters
    im_size = (640, 480)
    K = np.array([[572.41140, 0, 325.26110],
                  [0, 573.57043, 242.04899],
                  [0, 0, 0]])

    objs = ['Ape', 'Can', 'Cat', 'Driller', 'Duck', 'Eggbox', 'Glue', 'Holepuncher']
    model_fpath_mask = os.path.join('../../train_data/OcclusionChallengeICCV2015',
                                    'models_ply', '{0}.ply')

    pose_fpath_mask = os.path.join('../../train_data/OcclusionChallengeICCV2015',
                                   'poses', '{0}', '*.txt')
    models = []
    gt_poses = []
    for obj in objs:
        print 'Loading data:', obj
        model_fpath = model_fpath_mask.format(obj)
        models.append(inout.load_ply(model_fpath))

        gt_fpaths = sorted(glob.glob(pose_fpath_mask.format(obj)))
        gt_poses_obj = []
        for gt_fpath in gt_fpaths:
            gt_poses_obj.append(
                inout.load_gt_pose_dresden(gt_fpath))
        gt_poses.append(gt_poses_obj)

    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(16, 10))
    repeats = 100
    for i in range(repeats):
        print "multi object rendering {} / {}".format(i, repeats)
        rot_list = []
        pos_list = []
        indices = np.random.choice(len(objs), 1)
        model_list = []
        labels = []
        for obj_id, obj_name in enumerate(objs):
            # pos = np.random.rand(3) - 0.5
            # pos = np.zeros(3)
            # pos[2] += -2.0
            # pos = np.array([0,0,-1.5]).T
            # rot = np.eye(3)
            pose = gt_poses[obj_id][int(i)]
            if pose['R'].size != 0 and pose['t'].size != 0:
                pos = pose['t']
                rot = pose['R']
                pos_list.append(pos)
                rot_list.append(rot)
                model_list.append(models[obj_id])
                # rgb_ren, depth_ren = renderer.render(
                #     models[obj_id], im_size, K, rot, pos, 0.1, 4.0, mode='rgb+depth')
                labels.append(obj_id + 1)
        rgb_ren, depth_ren, label_ren  = multi_object_renderer.render(
            model_list, im_size, K, rot_list, pos_list, 0.1, 4.0,
            labels=labels, mode='rgb+depth+label')

        label_img = np.zeros((im_size[1], im_size[0], 3))
        n_colors = len(DEFAULT_COLORS)
        for lbl_id in labels:
            color = color_dict[DEFAULT_COLORS[lbl_id % n_colors]]
            label_img[(label_ren == lbl_id), :] = color

        # Clear axes
        for ax in axes.flatten():
            ax.clear()
        axes[0].imshow(rgb_ren.astype(np.uint8))
        axes[0].set_title('RGB image')
        axes[1].imshow(depth_ren)
        axes[1].set_title('Depth image')
        axes[2].imshow(label_img)
        axes[2].set_title('Label image')
        fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,
                            hspace=0.15, wspace=0.15)
        plt.draw()
        # # plt.pause(0.01)
        plt.waitforbuttonpress()
        for line in lines:
            Lectura = np.fromstring(line, dtype=float, sep=' ')
            Y = np.vstack([Y, Lectura[0]])

        Indmin = 1.1
        Indmax = 2
        Yhist = np.histogram(Y, bins=10, range=(int(Indmin), int(Indmax)))
        print(Yhist)
        #Analisis de caracteristicas para identificar si es carro o camioneta

        #plt.plot(Xhist, Ynew, marker='.')  # c='b')

        pyl.figure()
        pyl.title("Histograma de toda la señal completa")
        pyl.hist(Y)
        #pyl.show()
        pyl.waitforbuttonpress()

        plt.figure()
        plt.title("Histograma de toda la señal recortada")
        #plt.hist(Y)
        plt.hist(Y, bins=10, range=(int(Indmin), int(Indmax)))
        plt.xlim(1, 1.35)
        # pyl.show()
        plt.waitforbuttonpress()

except:
    print("Error al abrir el archivo")
    out_file.close()
Пример #13
0
def waitforbuttonpress():
    while plt.waitforbuttonpress(0.2) is None:
        if closed:
            return False
    return True
Пример #14
0
decoder_op = decoder(encoder_op)

# Prediction
y_pred = decoder_op
y_true = X

cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    total_batch = int(mnist.train.num_examples / batch_size)
    for epoch in range(training_epochs):
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={X: batch_x})
        if epoch % display_step == 0:
            print("Epoch:{0},cost={1}".format(epoch + 1, c))
    print("Optimization Done!")
    encode_decode = sess.run(
        y_pred, feed_dict={X: mnist.test.images[:examples_to_show]})
    f, a = plt.subplots(2, 10, figsize=(10, 2))
    for i in range(examples_to_show):
        a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
        a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))
    f.show()
    plt.draw()
    plt.waitforbuttonpress()
Пример #15
0
 [   2    0    0    3    0  883    2    0    2    0]
 [   5    2    0    0    1    3  944    0    3    0]
 [   1    0    9    2    0    0    0 1013    1    2]
 [   2    0    1    1    1    0    1    1  965    2]
 [   1    1    0    0    2    3    0    4    3  995]]
"""
net.load('example.h5')
print('Loaded...')
net.plot(os.path.basename(sys.argv[0]).split(".")[0] + ".png")
out = net.predict({'Input': images_test[:num_examples]})
rrand = list(range(images_test.shape[0]))[:10]
shuffle(rrand)
for i in rrand:
    o = out['Output'][i, 0]

    # plot
    plt.title("number: " + str(o))
    plt.imshow(images_test[i][:, :, 0], cmap='gray')
    plt.draw()
    plt.show(block=False)
    while plt.waitforbuttonpress(0) is None:
        pass
"""np.set_printoptions(threshold=np.nan)
a = out['Output']
b = labels_test
eq = a == b
accuracy = np.sum(eq)/eq.shape[0]
from sklearn.metrics import confusion_matrix
print('Accuracy: ' + str(accuracy))
print('Confusion Matrix:')
print(confusion_matrix(b, a))"""
Пример #16
0
def select_outlets(dem,
                   fd,
                   prefix,
                   hs=None,
                   outlet_filename='outlets.p',
                   color='r'):
    if hs is None:
        hs = d.Hillshade(elevation=dem, azimuth=320, inclination=20)

    plot_dem(dem, hs)

    keep_going = True

    while keep_going:
        zoom_ok = False
        print(
            '\nZoom or pan to view, \npress spacebar when ready to select point upstream of outlet:\n'
        )
        while not zoom_ok:
            zoom_ok = plt.waitforbuttonpress()
        print('\nClick on point upstream of outlet.')
        xy = plt.ginput(1)[0]
        xy_path = fd.search_down_flow_direction_from_xy_location(xy)
        plt.plot(xy)
        plt.plot(xy_path)
        xy_path_plot = list(zip(*xy_path))
        path = plt.plot(xy_path_plot[0], xy_path_plot[1], color + '-')
        print('\nClick on the outlet location.')
        xy = plt.ginput(1)[0]

        min_distance = 1E12

        for loc in xy_path:

            if (np.sqrt(
                    np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2))
                    < min_distance) or min_distance == 1E12:
                outlet_loc = loc
                min_distance = np.sqrt(
                    np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2))

        plt.figure(1)
        plt.plot(outlet_loc[0], outlet_loc[1], color + 'o')
        path.pop(0).remove()

        outlet_prefix = raw_input(
            'Type a name for this outlet (leaving this blank will prevent outlet from being saved and will complete the selection process: '
        )

        if outlet_prefix != '':
            import os.path
            if os.path.isfile(outlet_filename):
                outlets = p.load(open(outlet_filename, 'rb'))
            else:
                outlets = dict()

            this_tile = outlets.get(prefix, dict())
            this_tile[outlet_prefix] = outlet_loc

            outlets[prefix] = this_tile

            p.dump(outlets, open(outlet_filename, 'wb'))
        else:
            keep_going = False