Python matplotlib.pyplot.show() Examples

The following are code examples for showing how to use matplotlib.pyplot.show(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: s2g   Author: caesar0301   File: test.py    MIT License 6 votes vote down vote up
def test_point_projects_to_edge(self):
        # p = (114.83299055, 26.8892277)
        p = (121.428387, 31.027371)
        a = time.time()
        edges, segments = self.sg.point_projects_to_edges(p, 0.01)
        print(time.time() - a)

        if self.show_plots:
            plt.figure()
            s2g.plot_lines(MultiLineString(segments), color='orange')  # original roads
            for i in range(0, len(edges)):
                s, e = edges[i]
                sxy = self.sg.node_xy[s]
                exy = self.sg.node_xy[e]
                plt.plot([sxy[0], exy[0]], [sxy[1], exy[1]], color='green')  # graph edges
            plt.plot(p[0], p[1], color='red', markersize=12, marker='o')  # bridges
            plt.show() 
Example 2
Project: b2ac   Author: hbldh   File: point.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib Patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Point
            from b2ac.geometry.point import B2ACPoint

            p = B2ACPoint((3.0, 5.0))
            plt.gca().add_patch(Point(p.mpl_patch_arguments, color='g'))
            plt.show()

        """
        return self.point, 
Example 3
Project: b2ac   Author: hbldh   File: polygon.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Polygon
            from b2ac.geometry.polygon import B2ACPolygon

            p = B2ACPolygon([(2.1, 1.2), (5.2, 2.4), (1.0, 0.2)])
            plt.gca().add_patch(Polygon(
                p.mpl_patch_arguments, closed=True, fill=False, edgecolor='r')
            plt.show()

        """
        return self.polygon_points, 
Example 4
Project: b2ac   Author: hbldh   File: ellipse.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Ellipse
            from b2ac.ellipse import B2ACEllipse

            e = B2ACEllipse((3.0, 5.0), (2.0, 6.0, 1.57))
            plt.gca().add_patch(Ellipse(
                e.mpl_patch_arguments, fill=False, edgecolor='g'))
            plt.show()

        """
        return self.center_point, self.radii[0] * 2, self.radii[1] * 2, np.rad2deg(self.rotation_angle) 
Example 5
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_ranks(p, g, ladder):
    def get_names_ranks(data):
        ret = []
        for l in data:
            if float(l.extra[2][1]) > 7.:
                ret.append((l[1], len(data)))
            else:
                ret.append((l.name, l.rank))
        return ret

    graph_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_ranks(data))

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_ranks.svg')
    #plt.show() 
Example 6
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_level(p, g, ladder):
    def get_names_lvl(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[0][1]))
        return ret

    graph_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_lvl(data))

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_level.svg')
   # plt.show() 
Example 7
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_skill(p, g, ladder):
    def get_names_skill(data):
        ret = []
        for l in data:
            if float(l.extra[2][1]) > 7.:
                ret.append((l.name, 0.))
            else:
                ret.append((l.name, l.extra[1][1]))
        return ret

    graph_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_skill(data))

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_skill.svg')
  #  plt.show() 
Example 8
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 6 votes vote down vote up
def _capture2dImage(self, cameraId):
        # Capture Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture2DImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video_service.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth   = imageRGB[0]
        imageHeight  = imageRGB[1]
        array        = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image.
        image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png"
        im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo2d += 1
        im.show()

        return 
Example 9
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))


        clientRGB = self.video_service.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth  = imageRGB[0]
        imageHeight = imageRGB[1]
        array       = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)
        # Save the image.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example 10
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 votes vote down vote up
def _get_old_pred(bg_df, start_index, end_index, num_pred_minutes):
    #The number of 5 minute sections until the prediction (e.g. 30 minutes = 6 sections)
    pred_array_index = num_pred_minutes / DATA_SPACING

    actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, iob_pred_array, iob_pred_time_array, cob_pred_array, cob_pred_time_array, acob_pred_array, acob_pred_time_array = _get_raw_pred_array(bg_df, start_index, end_index, pred_array_index)

    eventual_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, 30)
    iob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, iob_pred_array, iob_pred_time_array, num_pred_minutes)
    cob_pred_data= _find_compare_array(actual_bg_array, actual_bg_time_array, cob_pred_array, cob_pred_time_array, num_pred_minutes)
    acob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, acob_pred_array, acob_pred_time_array, num_pred_minutes)

    return eventual_pred_data, iob_pred_data, cob_pred_data, acob_pred_data


#Plots old pred data given namedtuple of old data (eventualBG, acob, cob, or iob).
#Can show or save prediction plot based on show_pred_plot or save_pred_plot, respectively.
#Same goes for the Clarke Error grid with show_clarke_plot or save_clarke_plot, respectively.
#id_str, algorithm_str, minutes_str are strings of the ID, the prediction algorithm and the number of prediction minutes used for the title. 
Example 11
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 votes vote down vote up
def _plot_old_pred_data(old_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str):
    actual_bg_array = old_pred_data.result_actual_bg_array
    actual_bg_time_array = old_pred_data.result_actual_bg_time_array
    pred_array = old_pred_data.result_pred_array
    pred_time_array = old_pred_data.result_pred_time_array

    #Root mean squared error
    rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, pred_array))
    print "                Root Mean Squared Error: " + str(rms)
    print "                Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, pred_array))
    print "                R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, pred_array))

    plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, pred_array, id_str + " " + algorithm_str + " " + minutes_str)
    print "                Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4])
    if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png")
    if show_clarke_plot: plot.show()

    plt.clf()
    plt.plot(actual_bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-')
    plt.plot(pred_time_array, pred_array, label="BG Prediction", color='black', linestyle=':')
    plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis")
    plt.ylabel("Blood Glucose Level (mg/dl)")
    plt.xlabel("Time (minutes)")
    plt.legend(loc='upper left')

    # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER
    if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png")
    if show_pred_plot: plt.show()


#Function to analyze the old OpenAPS data 
Example 12
Project: Py-Utils   Author: LonamiWebs   File: memory.py    MIT License 6 votes vote down vote up
def access_all(self, refs, show=False, draw=False,
                   delay=0, delay_hit=None, delay_miss=None):
        """Accesses all the references (either a list, or a
           string, comma, semicolon, or space separated values)
        """
        if isinstance(refs, str):
            if ',' in refs:
                refs = [int(s.strip()) for s in refs.split(',')]
            elif ';' in refs:
                refs = [int(s.strip()) for s in refs.split(';')]
            else:
                refs = [int(s) for s in refs.split()]
        
        for r in refs:
            self.access(r, show=show, draw=draw, delay=delay,
                        delay_hit=delay_hit, delay_miss=delay_miss) 
Example 13
Project: Stock-Price-Prediction   Author: dhingratul   File: helper.py    MIT License 6 votes vote down vote up
def plot_mul(Y_hat, Y, pred_len):
    """
    PLots the predicted data versus true data

    Input: Predicted data, True Data, Length of prediction
    Output: return plot

    Note: Run from timeSeriesPredict.py
    """
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(Y, label='Y')
    # Print the predictions in its respective series-length
    for i, j in enumerate(Y_hat):
        shift = [None for p in range(i * pred_len)]
        plt.plot(shift + j, label='Y_hat')
        plt.legend()
    plt.show() 
Example 14
Project: Electrolyte_Analysis_FTIR   Author: Samuel-Buteau   File: quality_control_dataset.py    MIT License 6 votes vote down vote up
def handle(self, *args, **kwargs):
        if update_eli:
            for spec in FTIRSpectrum.objects.filter(preparation=HUMAN):
                print('filename: ', spec.filename, 'Supervized? ', spec.supervised)
                print('LiPF6: {}, EC: {}, EMC: {}, DMC: {}, DEC: {}'.format(
                    spec.LIPF6_mass_ratio,
                    spec.EC_mass_ratio,
                    spec.EMC_mass_ratio,
                    spec.DMC_mass_ratio,
                    spec.DEC_mass_ratio))

                samples = FTIRSample.objects.filter(spectrum=spec).order_by('index')
                plt.scatter([s.wavenumber for s in samples], [s.absorbance for s in samples])
                plt.show()
                x = input('Please enter KEEP/DELETE/UNSUPERVISED:')
                if 'KEEP' in x:
                    continue
                elif 'DELETE' in x:
                    spec.delete()
                elif 'UNSUPERVISED' in x:
                    spec.supervised = False
                    spec.save()
                else:
                    continue 
Example 15
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: capsulenet.py    MIT License 6 votes vote down vote up
def test(model, data):
    x_test, y_test = data
    y_pred, x_recon = model.predict(x_test, batch_size=100)
    print('-'*50)
    print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/y_test.shape[0])

    import matplotlib.pyplot as plt
    from utils import combine_images
    from PIL import Image

    img = combine_images(np.concatenate([x_test[:50],x_recon[:50]]))
    image = img * 255
    Image.fromarray(image.astype(np.uint8)).save("real_and_recon.png")
    print()
    print('Reconstructed images are saved to ./real_and_recon.png')
    print('-'*50)
    plt.imshow(plt.imread("real_and_recon.png", ))
    plt.show() 
Example 16
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: capsulenet-multi-gpu.py    MIT License 6 votes vote down vote up
def test(model, data):
    x_test, y_test = data
    y_pred, x_recon = model.predict(x_test, batch_size=100)
    print('-'*50)
    print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/y_test.shape[0])

    import matplotlib.pyplot as plt
    from utils import combine_images
    from PIL import Image

    img = combine_images(np.concatenate([x_test[:50],x_recon[:50]]))
    image = img * 255
    Image.fromarray(image.astype(np.uint8)).save("real_and_recon.png")
    print()
    print('Reconstructed images are saved to ./real_and_recon.png')
    print('-'*50)
    plt.imshow(plt.imread("real_and_recon.png", ))
    plt.show() 
Example 17
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc(y_true, y_pred, plot=False):
    """
    TODO
    :param y_true: ground truth
    :param y_pred: predictions
    :param plot:
    :return:
    """
    fpr, tpr, _ = roc_curve(y_true, y_pred)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 18
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc_rfeinman(probs_neg, probs_pos, plot=False):
    """
    TODO
    :param probs_neg:
    :param probs_pos:
    :param plot:
    :return:
    """
    probs = np.concatenate((probs_neg, probs_pos))
    labels = np.concatenate((np.zeros_like(probs_neg), np.ones_like(probs_pos)))
    fpr, tpr, _ = roc_curve(labels, probs)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 19
Project: oslodatascience-rl   Author: Froskekongen   File: space_invaders4.py    MIT License 6 votes vote down vote up
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
    """ convert the 210x160x3 uint8 frame into a 7056 float vector """
    processed_observation = remove_color(preprocess(input_observation))
    processed_observation = processed_observation.astype(np.float).ravel()

    # subtract the previous frame from the current one so we are only processing on changes in the game
    if prev_processed_observation is not None:
        input_observation = processed_observation - prev_processed_observation
        # B = np.reshape(input_observation, (-1, 84))
        # plt.imshow(np.array(np.squeeze(B)))
        # plt.show()
    else:
        input_observation = np.zeros(input_dimensions)
    # store the previous frame so we can subtract from it next time
    prev_processed_observations = processed_observation
    return input_observation, prev_processed_observations 
Example 20
Project: oslodatascience-rl   Author: Froskekongen   File: space_invaders3.py    MIT License 6 votes vote down vote up
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
    """ convert the 210x160x3 uint8 frame into a 6400 float vector """
    # processed_observation = input_observation
    # processed_observation = remove_color(processed_observation)
    # processed_observation = remove_background(processed_observation)
    # processed_observation[processed_observation != 0] = 1 # everything else (paddles, ball) just set to 1
    # # Convert from 80 x 80 matrix to 6400 x 1 matrix
    #
    # processed_observation = processed_observation[25:195,]

    processed_observation = remove_color(preprocess(input_observation))
    processed_observation = processed_observation.astype(np.float).ravel()

    # subtract the previous frame from the current one so we are only processing on changes in the game
    if prev_processed_observation is not None:
        input_observation = processed_observation - prev_processed_observation
        # B = np.reshape(input_observation, (-1, 84))
        # plt.imshow(np.array(np.squeeze(B)))
        # plt.show()
    else:
        input_observation = np.zeros(input_dimensions)
    # store the previous frame so we can subtract from it next time
    prev_processed_observations = processed_observation
    return input_observation, prev_processed_observations 
Example 21
Project: deep-learning-note   Author: wdxtub   File: 3_linear_regression_raw.py    MIT License 6 votes vote down vote up
def generate_dataset(true_w, true_b):
    num_examples = 1000

    features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
    # 真实 label
    labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
    # 添加噪声
    labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
    # 展示下分布
    plt.scatter(features[:, 1].numpy(), labels.numpy(), 1)
    plt.show()
    
    return features, labels


# batch 读取数据集 
Example 22
Project: deep-learning-note   Author: wdxtub   File: simulate_sin.py    MIT License 6 votes vote down vote up
def run_eval(sess, test_X, test_y):
    ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
    ds = ds.batch(1)
    X, y = ds.make_one_shot_iterator().get_next()

    with tf.variable_scope("model", reuse=True):
        prediction, _, _ = lstm_model(X, [0.0], False)
        predictions = []
        labels = []
        for i in range(TESTING_EXAMPLES):
            p, l = sess.run([prediction, y])
            predictions.append(p)
            labels.append(l)

    predictions = np.array(predictions).squeeze()
    labels = np.array(labels).squeeze()
    rmse = np.sqrt(((predictions-labels) ** 2).mean(axis=0))
    print("Mean Square Error is: %f" % rmse)

    plt.figure()
    plt.plot(predictions, label='predictions')
    plt.plot(labels, label='real_sin')
    plt.legend()
    plt.show() 
Example 23
Project: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    MIT License 5 votes vote down vote up
def plot_learning(self):
        """
        Plot the fitness through iterations.
        """
        plt.plot([i for i in range(len(self.fitness_list))], self.fitness_list)
        plt.ylabel("Fitness")
        plt.xlabel("Iteration")
        plt.show() 
Example 24
Project: s2g   Author: caesar0301   File: test.py    MIT License 5 votes vote down vote up
def test_subgraph_within_box(self):
        bounding_box = box(121.428387, 31.027371, 121.430863, 31.030227)
        a = time.time()
        subgraph = self.sg.subgraph_within_box(bounding_box)
        print(time.time() - a)
        if self.show_plots:
            plt.figure()
            nx.draw(subgraph, pos=self.sg.node_xy, node_size=50)
            plt.show() 
Example 25
Project: SyNEThesia   Author: RunOrVeith   File: live_viewer.py    MIT License 5 votes vote down vote up
def display(self, image_generator):
        im = plt.imshow(np.zeros((1, 1, 3)), animated=True)
        def update(frame, *_):
            im.set_array(frame)
            return im,

        ani = FuncAnimation(self.fig, func=update, frames=image_generator, interval=self.pause_time, blit=True)
        plt.show() 
Example 26
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 5 votes vote down vote up
def graph_skill_topn(p, g, ladder, n):
    def get_names_skill(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[1][1]))
        return ret

    def get_top_n(data):
        tup = sorted(data, key=lambda x: float(x[1]))
        names = [t[0] for t in tup[-n:]]
        return names

    graph_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_skill(data))

    names = sorted(get_top_n(graph_data[-1]))
    graph_data = [sorted(x) for x in get_subset(graph_data, names)]

    ys = data_to_yarr(graph_data)
    for i in range(len(ys)):
        y = np.array(ys[i])
        plt.plot(range(len(y)), y, label = names[i])
    plt.legend(loc=3, ncol=len(names)/2)
    pylab.savefig('graph_skill_topn.svg')
 #   plt.show() 
Example 27
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 5 votes vote down vote up
def graph_skill_error(p, g, ladder):
    def get_names_skill(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[1][1]))
        return ret

    def get_names_err(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[2][1]))
        return ret

    def get_top_n(data):
        tup = sorted(data, key=lambda x: float(x[1]))
        names = [t[0] for t in tup[:6]]
        return names

    graph_data = []
    err_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_skill(data))
        err_data.append(get_names_err(data))
    names = sorted(get_top_n(err_data[-1]))
    graph_data = [sorted(x) for x in get_subset(graph_data, names)]
    err_data = [sorted(x) for x in get_subset(err_data, names)]

    ys = data_to_yarr(graph_data)
    errs = data_to_yarr(err_data)
    for i in range(len(ys)):
        err = np.array(errs[i])
        y = np.array(ys[i])
        plt.fill_between(range(len(y)), y+err, y-err, alpha=0.25, color=COLOURS[i])
        plt.plot(range(len(y)), y, COLOURS[i] +'-', label = names[i])
        plt.plot(y)
    plt.legend(loc=3, ncol=len(names)/2)
    pylab.savefig('graph_error.svg')
#    plt.show() 
Example 28
Project: projection-methods   Author: akshayka   File: circles.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    x = cp.Variable(2)
    r = 10
    left_circle = ConvexSet(x, [cp.square(x[0] + r) + cp.square(x[1]) <= r**2])
    right_circle = ConvexSet(x, [cp.square(x[0] - r) + cp.square(x[1]) <= r**2])

    problem = FeasibilityProblem([left_circle, right_circle], np.array([0, 0]))

    initial_iterate = np.array([0, r])
    max_iters = 10

    plt.figure()
    plot_circles(r)
    solver = AltP(max_iters=max_iters, initial_iterate=initial_iterate)
    solver.solve(problem)
    plot_iterates(solver.all_iterates, 'Alternating Projections')

    solver = Polyak(max_iters=max_iters, initial_iterate=initial_iterate)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'Polyak\'s acceleration')

    solver = APOP(max_iters=max_iters, initial_iterate=initial_iterate,
        average=False)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'APOP')
    plt.title('Motivating APOP: Circles')
    plt.legend()
    plt.show() 
Example 29
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def run(self):
        self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")

        self.motion_service.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.1)

        self.create_callbacks()
        # self.startDLServer()
        self._addTopic()

        # graphplots
        self._initialisePlot()
        ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)


        # loop on, wait for events until manual interruption
        try:
            # while True:
            #     time.sleep(1)
            # starting graph plot
            plt.show() # blocking call hence no need for while(True)

        except KeyboardInterrupt:
            self._printLogs("Interrupted by user, shutting down", "FAIL")
            self._cleanUp()

            self._printLogs("Waiting for the robot to be in rest position", "FAIL")
            # self.motion_service.rest()
            sys.exit(0)

        return 
Example 30
Project: sfcc   Author: kv-kunalvyas   File: auxiliary.py    MIT License 5 votes vote down vote up
def plotLearningCurves(train, classifier):
    #P.show()
    X = train.values[:, 1::]
    y = train.values[:, 0]

    train_sizes, train_scores, test_scores = learning_curve(
            classifier, X, y, cv=10, n_jobs=-1, train_sizes=np.linspace(.1, 1., 10), verbose=0)

    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.figure()
    plt.title("Learning Curves")
    plt.legend(loc="best")
    plt.xlabel("Training samples")
    plt.ylabel("Error Rate")
    plt.ylim((0, 1))
    plt.gca().invert_yaxis()
    plt.grid()

    # Plot the average training and test score lines at each training set size
    plt.plot(train_sizes, train_scores_mean, 'o-', color="b", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="Test score")

    # Plot the std deviation as a transparent range at each training set size
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
                     alpha=0.1, color="b")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
                     alpha=0.1, color="r")

    # Draw the plot and reset the y-axis
    plt.draw()
    plt.gca().invert_yaxis()

    # shuffle and split training and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)
    classifier.fit(X_train, y_train)
    plt.show() 
Example 31
Project: curriculum-dropout   Author: pmorerio   File: load.py    GNU General Public License v3.0 5 votes vote down vote up
def main():

	data_ = open('../data_dir.txt','r')
	datasets_dir = data_.readline().split()[0]
	double_mnist, labels, _, _= doubleMnist(datasets_dir)	
	print 'label', labels[110,:]
	plt.imshow(double_mnist[110,:,:])
	plt.show() 
Example 32
Project: OpenAPS   Author: medicinexlab   File: bglomb.py    MIT License 5 votes vote down vote up
def _get_lomb_scargle(bg_df, start_index, end_index, plot_lomb_array):
        bg_time_array, bg_value_array, bg_gap_start_time, bg_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'bg')
        iob_time_array, iob_value_array, iob_gap_start_time, iob_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'IOB')
        cob_time_array, cob_value_array, cob_gap_start_time, cob_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'COB')

        #Keep track of the data start and end times in the array
        data_gap_start_time = bg_gap_start_time + iob_gap_start_time + cob_gap_start_time
        data_gap_end_time = bg_gap_end_time + iob_gap_end_time + cob_gap_end_time

        period = np.linspace(0, int(bg_time_array.max()), int(bg_time_array.max()) + 1) #set period to be as large as possible

        bg_lomb = _run_lomb_scargle(bg_time_array, bg_value_array, period)
        iob_lomb = _run_lomb_scargle(iob_time_array, iob_value_array, period)
        cob_lomb = _run_lomb_scargle(cob_time_array, cob_value_array, period)

        #Set all bg/cob values below zero equal to zero (iob can be negative if it is below baseline levels)
        bg_lomb[bg_lomb < 0] = 0
        cob_lomb[cob_lomb < 0] = 0

        #Plot lomb-scargle if values in the plot_lomb_array
        if len(plot_lomb_array) > 0:
            plt.clf()
            if "bg" in plot_lomb_array: _plot_lomb(period, bg_lomb, bg_time_array, bg_value_array, "BG")
            if "iob" in plot_lomb_array: _plot_lomb(period, iob_lomb, iob_time_array, iob_value_array, "IOB")
            if "cob" in plot_lomb_array: _plot_lomb(period, cob_lomb, cob_time_array, cob_value_array, "COB")
            plt.legend(loc='upper left')
            plt.show()

        return period, bg_lomb, iob_lomb, cob_lomb, data_gap_start_time, data_gap_end_time


#Class to store the lomb data 
Example 33
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 5 votes vote down vote up
def analyze_old_pred_data(bg_df, old_pred_algorithm_array, start_test_index, end_test_index, pred_minutes, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str):
    """
    Function that analyzes the old OpenAPS prediction models (eventualBG, aCOB, COB, and IOB)
    based on what is put in the old_pred_algorithm_array. If it is empty, nothing will be plotted.
    Since all the algorithms are calculated every 5 minutes, pred_minutes must be a multiple of 5.
    eventualBG is only calculated by 30 minutes, so it will always be 30 minutes.
    It will save the prediction plot if save_pred_plot is True and the clarke plot if save_clarke_plot is True.
    It will show the prediction plot if show_pred_plot is true and the clarke plot if show_clarke_plot is True.

    Input:      bg_df                           Pandas dataframe of all of the data from ./data/[id_str]/devicestatus.json
                old_pred_algorithm_array        The array of the original OpenAPS prediction algorithms that you want to receive
                                                    data from. It can contain any/none of the following: "eventualBG", "acob", "cob", "iob"
                start_test_index                The starting index of the testing data
                end_test_index                  The ending index of the testing data
                pred_minutes                    The number of minutes in the future the prediction is for (predicion horizon). Must be a multiple of 5
                show_pred_plot                  Boolean to show the prediction plot
                save_pred_plot                  Boolean to save the prediction plot
                show_clarke_plot                Boolean to show the Clarke Error Grid Plot
                save_clarke_plot                Boolean to save the Clarke Error Grid Plot
                id_str                          The ID of the person as a string. Used for the title

    Output:     None
    Usage:      analyze_old_pred_data(bg_df, ['iob', 'cob'], 1500, 0, 30, True, False, True, False, "00000001")
    """

    if pred_minutes % 5 != 0: raise Exception("The prediction minutes is not a multiple of 5.")
    eventual_pred_data, iob_pred_data, cob_pred_data, acob_pred_data = _get_old_pred(bg_df, start_test_index, end_test_index, pred_minutes)
    if 'eventualBG' in old_pred_algorithm_array and pred_minutes == EVENTUALBG_PRED_MINUTES:
        print("        eventualBG")
        _plot_old_pred_data(eventual_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "eventualBG", "Pred" + str(30))
    if 'iob' in old_pred_algorithm_array:
        print("        iob")
        _plot_old_pred_data(iob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "IOB", "Pred" + str(pred_minutes))
    if 'cob' in old_pred_algorithm_array:
        print("        cob")
        _plot_old_pred_data(cob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "COB", "Pred" + str(pred_minutes))
    if 'acob' in old_pred_algorithm_array:
        print("        acob")
        _plot_old_pred_data(acob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "aCOB", "Pred" + str(pred_minutes)) 
Example 34
Project: FRIDA   Author: LCAV   File: point_cloud.py    MIT License 5 votes vote down vote up
def plot(self, axes=None, show_labels=True, **kwargs):

        if self.dim == 2:

            # Create a figure if needed
            if axes is None:
                axes = plt.subplot(111)

            axes.plot(self.X[0,:], self.X[1,:], **kwargs)
            axes.axis(aspect='equal')
            plt.show()


        elif self.dim == 3:
            if axes is None:
                fig = plt.figure()
                axes = fig.add_subplot(111, projection='3d')
            axes.scatter(self.X[0,:], self.X[1,:], self.X[2,:], **kwargs)
             
            axes.set_xlabel('X')
            axes.set_ylabel('Y')
            axes.set_zlabel('Z')
            plt.show()

        if show_labels and self.labels is not None:
            eps = np.linalg.norm(self.X[:,0] - self.X[:,1])/100
            for i in xrange(self.m):
                if self.dim == 2:
                    axes.text(self.X[0,i]+eps, self.X[1,i]+eps, self.labels[i])
                elif self.dim == 3:
                    axes.text(self.X[0,i]+eps, self.X[1,i]+eps, self.X[2,i]+eps, self.labels[i], None)

        return axes 
Example 35
Project: FRIDA   Author: LCAV   File: generators.py    MIT License 5 votes vote down vote up
def gen_dirty_img(visi, pos_mic_x, pos_mic_y, omega_band, sound_speed, phi_plt):
    """
    Compute the dirty image associated with the given measurements. Here the Fourier transform
    that is not measured by the microphone array is taken as zero.
    :param visi: the measured visibilites
    :param pos_mic_x: a vector contains microphone array locations (x-coordinates)
    :param pos_mic_y: a vector contains microphone array locations (y-coordinates)
    :param omega_band: mid-band (ANGULAR) frequency [radian/sec]
    :param sound_speed: speed of sound
    :param phi_plt: plotting grid (azimuth on the circle) to show the dirty image
    :return:
    """
    img = np.zeros(phi_plt.size, dtype=complex)
    x_plt, y_plt = polar2cart(1, phi_plt)
    num_mic = pos_mic_x.size

    pos_mic_x_normalised = pos_mic_x / (sound_speed / omega_band)
    pos_mic_y_normalised = pos_mic_y / (sound_speed / omega_band)

    count_visi = 0
    for q in xrange(num_mic):
        p_x_outer = pos_mic_x_normalised[q]
        p_y_outer = pos_mic_y_normalised[q]
        for qp in xrange(num_mic):
            if not q == qp:
                p_x_qqp = p_x_outer - pos_mic_x_normalised[qp]  # a scalar
                p_y_qqp = p_y_outer - pos_mic_y_normalised[qp]  # a scalar
                # <= the negative sign converts DOA to propagation vector
                img += visi[count_visi] * \
                       np.exp(-1j * (p_x_qqp * x_plt + p_y_qqp * y_plt))
                count_visi += 1
    return img / (num_mic * (num_mic - 1)) 
Example 36
Project: atomospy   Author: Shikhar1998   File: plotter_lorentz.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_lorentz(L, L_, style = 'ro'):
    """
    For plotting the four dimensional plots the
    fourth dimension in a three dimension

    Default style = 'ro'
    """

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    if S.ComplexInfinity in L or S.ComplexInfinity in L_:
        raise("ComplexError: Cannot plot with complex quantities")
    ax.scatter([L[0], L_[0]], [L[1], L_[1]],
             [L[2], L_[2]], [L[2], L_[2]], cmap=plt.hot())
    plt.show() 
Example 37
Project: Py-Utils   Author: LonamiWebs   File: memory.py    MIT License 5 votes vote down vote up
def plot_ways(policy='lru'):
    if np is None or plt is None:
        print('numpy and matplotlib are required for plotting')
        return
    
    fig, ax = plt.subplots()
    refs = '1 65 129 193 1 129 1 65 129 1 1 65 129 129'
    psize = 4
    partc = 16
    
    ways = []
    hits = []
    miss = []
    
    wayc = 1 
    while wayc <= partc:
        c = Cache(psize, partc, wayc, policy)
        c.access_all(refs)
        ways.append(wayc)
        hits.append(c.hits)
        miss.append(c.misses)
        wayc *= 2
        print(c)
    
    ax.plot(ways, hits, 'go-', label='hits', linewidth=1)
    ax.plot(ways, miss, 'ro-', label='misses', linewidth=1)
    
    ax.set_ylabel('Count (using '+policy.upper()+')')
    ax.set_xlabel('Number of ways')
    ax.legend()
    
    ax.set_xscale('log', basex=2)
    plt.show() 
Example 38
Project: Py-Utils   Author: LonamiWebs   File: memory.py    MIT License 5 votes vote down vote up
def plot_psize():
    if np is None or plt is None:
        print('numpy and matplotlib are required for plotting')
        return
    
    fig, ax = plt.subplots()
    refs = '1 4 8 5 20 17 19 56 9 11 4 43 5 6 9 17 181'
    psize = 1
    partc = 16
    
    xaxe = []
    hits = []
    miss = []
    
    while partc >= 1:
        c = Cache(psize, partc)
        c.access_all(refs)
        xaxe.append(psize)
        hits.append(c.hits)
        miss.append(c.misses)
        psize *= 2
        partc //= 2
        print(c)
    
    ax.plot(xaxe, hits, 'go-', label='hits', linewidth=1)
    ax.plot(xaxe, miss, 'ro-', label='misses', linewidth=1)
    
    ax.set_ylabel('Count')
    ax.set_xlabel('Partition size (total size constant)')
    ax.legend()
    
    ax.set_xscale('log', basex=2)
    plt.show() 
Example 39
Project: ml_news_popularity   Author: khaledJabr   File: lr.py    MIT License 5 votes vote down vote up
def plot(self):
        lw = 2
        plt.scatter(range(len(self.targets)), self.targets, color='darkorange', label='data')
        plt.scatter(range(len(self.predicted)), self.predicted, color='cornflowerblue', lw=lw, label='Polynomial model')
        plt.xlabel('Data')
        plt.ylabel('Target')
        plt.title('Lasso Regression')
        plt.legend()
        plt.show() 
Example 40
Project: fbpconv_tf   Author: panakino   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_prediction(x_test, y_test, prediction, save=False):
    import matplotlib
    import matplotlib.pyplot as plt
    
    test_size = x_test.shape[0]
    fig, ax = plt.subplots(test_size, 3, figsize=(12,12), sharey=True, sharex=True)
    
    x_test = crop_to_shape(x_test, prediction.shape)
    y_test = crop_to_shape(y_test, prediction.shape)
    
    ax = np.atleast_2d(ax)
    for i in range(test_size):
        cax = ax[i, 0].imshow(x_test[i])
        plt.colorbar(cax, ax=ax[i,0])
        cax = ax[i, 1].imshow(y_test[i, ..., 1])
        plt.colorbar(cax, ax=ax[i,1])
        pred = prediction[i, ..., 1]
        pred -= np.amin(pred)
        pred /= np.amax(pred)
        cax = ax[i, 2].imshow(pred)
        plt.colorbar(cax, ax=ax[i,2])
        if i==0:
            ax[i, 0].set_title("x")
            ax[i, 1].set_title("y")
            ax[i, 2].set_title("pred")
    fig.tight_layout()
    
    if save:
        fig.savefig(save)
    else:
        fig.show()
        plt.show() 
Example 41
Project: RandomFourierFeatures   Author: tiskw   File: sample_rff_regression.py    MIT License 5 votes vote down vote up
def main():

    ### Fix seed for random fourier feature calclation
    pyrff.seed(111)

    ### Prepare training data
    Xs_train = np.linspace(0, 3, 21).reshape((21, 1))
    ys_train = np.sin(Xs_train**2)
    Xs_test  = np.linspace(0, 3, 101).reshape((101, 1))
    ys_test  = np.sin(Xs_test**2)

    ### Create classifier instance
    reg = pyrff.RFFRegression(dim_output = 8, std = 0.5)

    ### Train regression with random fourier features
    reg.fit(Xs_train, ys_train)

    ### Conduct prediction for the test data
    predict = reg.predict(Xs_test)

    ### Plot regression results
    mpl.figure(0)
    mpl.title("Regression for function y = sin(x^2) with RFF")
    mpl.xlabel("X")
    mpl.ylabel("Y")
    mpl.plot(Xs_train, ys_train, "o")
    mpl.plot(Xs_test,  ys_test,  ".")
    mpl.plot(Xs_test,  predict,  "-")
    mpl.legend(["Training data", "Test data", "Prediction by RFF regression"])
    mpl.grid()
    mpl.show() 
Example 42
Project: mmdetection   Author: open-mmlab   File: coco_error_analysis.py    Apache License 2.0 5 votes vote down vote up
def makeplot(rs, ps, outDir, class_name, iou_type):
    cs = np.vstack([
        np.ones((2, 3)),
        np.array([.31, .51, .74]),
        np.array([.75, .31, .30]),
        np.array([.36, .90, .38]),
        np.array([.50, .39, .64]),
        np.array([1, .6, 0])
    ])
    areaNames = ['allarea', 'small', 'medium', 'large']
    types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN']
    for i in range(len(areaNames)):
        area_ps = ps[..., i, 0]
        figure_tile = iou_type + '-' + class_name + '-' + areaNames[i]
        aps = [ps_.mean() for ps_ in area_ps]
        ps_curve = [
            ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps
        ]
        ps_curve.insert(0, np.zeros(ps_curve[0].shape))
        fig = plt.figure()
        ax = plt.subplot(111)
        for k in range(len(types)):
            ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5)
            ax.fill_between(
                rs,
                ps_curve[k],
                ps_curve[k + 1],
                color=cs[k],
                label=str('[{:.3f}'.format(aps[k]) + ']' + types[k]))
        plt.xlabel('recall')
        plt.ylabel('precision')
        plt.xlim(0, 1.)
        plt.ylim(0, 1.)
        plt.title(figure_tile)
        plt.legend()
        # plt.show()
        fig.savefig(outDir + '/{}.png'.format(figure_tile))
        plt.close(fig) 
Example 43
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot_log(filename, show=True):
    # load data
    keys = []
    values = []
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if keys == []:
                for key, value in row.items():
                    keys.append(key)
                    values.append(float(value))
                continue

            for _, value in row.items():
                values.append(float(value))

        values = np.reshape(values, newshape=(-1, len(keys)))
        values[:,0] += 1

    fig = plt.figure(figsize=(4,6))
    fig.subplots_adjust(top=0.95, bottom=0.05, right=0.95)
    fig.add_subplot(211)
    for i, key in enumerate(keys):
        if key.find('loss') >= 0 and not key.find('val') >= 0:  # training loss
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training loss')

    fig.add_subplot(212)
    for i, key in enumerate(keys):
        if key.find('acc') >= 0:  # acc
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training and validation accuracy')

    # fig.savefig('result/log.png')
    if show:
        plt.show() 
Example 44
Project: Sessile.drop.analysis   Author: mvgorcum   File: GUI_sessile_drop_analysis.py    GNU General Public License v3.0 5 votes vote down vote up
def plotstuff(typexplot,typeyplot,logxbool,logybool,pxscale,fps):
    x=np.float()
    y=np.float()
    if typexplot==1:
        x=thetal
    elif typexplot==2:
        x=thetar
    elif typexplot==3:
        x=dropvolume*pxscale**3
    elif typexplot==3:
        x=leftspeed*pxscale*fps
    elif typexplot==4:
        x=rightspeed*pxscale*fps
    else:
        print('no x variable set')
    if typeyplot==1:
        y=thetal
    elif typeyplot==2:
        y=thetar
    elif typeyplot==3:
        y=dropvolume
    elif typeyplot==3:
        y=leftspeed
    elif typeyplot==4:
        y=rightspeed
    else:
        print('no y variable set')
    if x.size==1 or y.size==1:
        plt.scatter(x,y)
    else:
        plt.plot(x,y)
    
    if logxbool:
        plt.xscale('log')
    if logybool:
        plt.yscale('log')
    plt.show() 
Example 45
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 46
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 47
Project: voice-recognition   Author: golabies   File: cluster.py    MIT License 5 votes vote down vote up
def show(self):
        y = self.signal
        x = np.arange(len(y))
        plt.scatter(x, y, c=self.labels, s=0.1)
        plt.show() 
Example 48
Project: voice-recognition   Author: golabies   File: filters.py    MIT License 5 votes vote down vote up
def show(func, *inputs):
        x = func(*inputs)
        y = np.arange(len(x))
        plt.plot(y, x)
        plt.show() 
Example 49
Project: voice-recognition   Author: golabies   File: read_data.py    MIT License 5 votes vote down vote up
def show(self):
        for i in range(len(self.voice)):
            plt.plot(np.arange(len(self.voice[i])), self.voice[i]+i*5)
        plt.show() 
Example 50
Project: voice-recognition   Author: golabies   File: signal_fft.py    MIT License 5 votes vote down vote up
def show(self):
        plt.plot(self.freq, np.log10(self.out_put))
        plt.show()