Python pylab 模块,title() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.title()

项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def twoDimensionalScatter(title, title_x, title_y,
                          x, y,
                          lim_x = None, lim_y = None,
                          color = 'b', size = 20, alpha=None):
    """
    Create a two-dimensional scatter plot.

    INPUTS
    """
    pylab.figure()

    pylab.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')

    pylab.xlabel(title_x)
    pylab.ylabel(title_y)
    pylab.title(title)
    if type(color) is not str:
        pylab.colorbar()

    if lim_x:
        pylab.xlim(lim_x[0], lim_x[1])
    if lim_y:
        pylab.ylim(lim_y[0], lim_y[1])

############################################################
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_dataset(X, color='blue', title=None, save=None):
    n_components = 2
    pca = PCA(n_components)
    pca.fit(X)
    x = pca.transform(X)
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(x[:, 0], x[:, 1], c=color, s=5, lw=0.1)
    ax.grid(True)
    if title is None:
        ax.set_title("Dataset ({} samples)".format(X.shape[0]))
    else:
        ax.set_title(title + " ({} samples)".format(X.shape[0]))
    ax.set_xlabel("1st component")
    ax.set_ylabel("2nd component")
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_loss_curve(losss, title=None, save=None):
    '''Plot loss curve'''
    x_min = 1
    x_max = len(losss) - 1
    fig = pylab.figure()
    ax = fig.gca()
    ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid')
    ax.grid(True, which='both')
    if title is None:
        ax.set_title("Loss curve")
    else:
        ax.set_title(title)
    ax.set_xlabel("iteration")
    ax.set_ylabel("loss")
    ax.set_xlim([x_min - 1, x_max + 1])
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def display_results_figure(results, METRIC):
    import pylab as pb
    color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results))))
    plots = []
    for method in results.keys():
        x = []
        y = []
        for train_perc in sorted(results[method].keys()):
            x.append(train_perc)
            y.append(results[method][train_perc][0])
        c = next(color)
        (pi, ) = pb.plot(x, y, color=c)
        plots.append(pi)
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    pb.legend(plots, map(method_name_mapper, results.keys()),
              prop=fontP, bbox_to_anchor=(0.6, .65))
    pb.xlabel('#Tweets from target rumour for training')
    pb.ylabel('Accuracy')
    pb.title(METRIC.__name__)
    pb.savefig('incrementing_training_size.png')
项目:PortfolioTimeSeriesAnalysis    作者:MizioAnd    | 项目源码 | 文件源码
def predicted_vs_actual_y_xgb(self, xgb, best_nrounds, xgb_params, x_train_split, x_test_split, y_train_split,
                                  y_test_split, title_name):
        # Split the training data into an extra set of test
        # x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        dtrain_split = xgb.DMatrix(x_train_split, label=y_train_split)
        dtest_split = xgb.DMatrix(x_test_split)
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        gbdt = xgb.train(xgb_params, dtrain_split, best_nrounds)
        y_predicted = gbdt.predict(dtest_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual y')
        plt.ylabel('Predicted y')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
项目:ndparse    作者:neurodata    | 项目源码 | 文件源码
def display_pr_curve(precision, recall):
    # following examples from sklearn

    # TODO:  f1 operating point

    import pylab as plt
    # Plot Precision-Recall curve
    plt.clf()
    plt.plot(recall, precision, label='Precision-Recall curve')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1))
    plt.legend(loc="lower left")
    plt.show()
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def plotaffine(aff, RR, DD, exag=1000, affineOnly=False, doclf=True, **kwargs):
    import pylab as plt
    if doclf:
        plt.clf()
    if affineOnly:
        dr,dd = aff.getAffineOffset(RR, DD)
    else:
        rr,dd = aff.apply(RR, DD)
        dr = rr - RR
        dd = dd - DD
    #plt.plot(RR, DD, 'r.')
    #plt.plot(RR + dr*exag, DD + dd*exag, 'bx')
    plt.quiver(RR, DD, exag*dr, exag*dd,
               angles='xy', scale_units='xy', scale=1,
               pivot='middle', color='b', **kwargs)
               #pivot='tail'
    ax = plt.axis()
    plt.plot([aff.getReferenceRa()], [aff.getReferenceDec()], 'r+', mew=2, ms=5)
    plt.axis(ax)
    esuf = ''
    if exag != 1.:
        esuf = ' (x %g)' % exag
    plt.title('Affine transformation found' + esuf)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_rectified(self):
        import pylab
        pylab.title('rectified')
        pylab.imshow(self.rectified)

        for line in self.vlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_original(self):
        import pylab
        pylab.title('original')
        pylab.imshow(self.data)

        for line in self.lines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='blue', alpha=0.3)

        for line in self.vlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self):
        """ Plot the layer data (for debugging)
        :return: The current figure
        """
        import pylab as pl
        aspect = self.nrows / float(self.ncols)
        figure_width = 6 #inches

        rows = max(1, int(np.sqrt(self.nlayers)))
        cols = int(np.ceil(self.nlayers/rows))
        # noinspection PyUnresolvedReferences
        pallette = {i:rgb for (i, rgb) in enumerate(pl.cm.jet(np.linspace(0, 1, 4), bytes=True))}
        f, a = pl.subplots(rows, cols)
        f.set_size_inches(6 * cols, 6 * rows)
        a = a.flatten()
        for i, label in enumerate(self.label_names):
            pl.sca(a[i])
            pl.title(label)
            pl.imshow(self.color_data)
            pl.imshow(colorize(self.label_data[:, :, i], pallette), alpha=0.5)
            # axis('off')
        return f
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self, overlay_alpha=0.5):
        import pylab as pl
        rows = int(sqrt(self.layers()))
        cols = int(ceil(self.layers()/rows))

        for i in range(rows*cols):
            pl.subplot(rows, cols, i+1)
            pl.axis('off')
            if i >= self.layers():
                continue
            pl.title('{}({})'.format(self.labels[i], i))
            pl.imshow(self.image)
            pl.imshow(colorize(self.features[i].argmax(0),
                               colors=np.array([[0,     0, 255],
                                                [0,   255, 255],
                                                [255, 255, 0],
                                                [255, 0,   0]])),
                      alpha=overlay_alpha)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotPopScore(population, fitness=False):
   """ Plot the population score distribution

   Example:
      >>> Interaction.plotPopScore(population)

   :param population: population object (:class:`GPopulation.GPopulation`)
   :param fitness: if True, the fitness score will be used, otherwise, the raw.
   :rtype: None

   """
   score_list = getPopScores(population, fitness)
   pylab.plot(score_list, 'o')
   pylab.title("Plot of population score distribution")
   pylab.xlabel('Individual')
   pylab.ylabel('Score')
   pylab.grid(True)
   pylab.show()

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotHistPopScore(population, fitness=False):
   """ Population score distribution histogram

   Example:
      >>> Interaction.plotHistPopScore(population)

   :param population: population object (:class:`GPopulation.GPopulation`)
   :param fitness: if True, the fitness score will be used, otherwise, the raw.
   :rtype: None

   """
   score_list = getPopScores(population, fitness)
   n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1)
   pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--')
   pylab.xlabel('Score')
   pylab.ylabel('Frequency')
   pylab.grid(True)
   pylab.title("Plot of population score distribution")
   pylab.show()

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotPopScore(population, fitness=False):
   """ Plot the population score distribution

   Example:
      >>> Interaction.plotPopScore(population)

   :param population: population object (:class:`GPopulation.GPopulation`)
   :param fitness: if True, the fitness score will be used, otherwise, the raw.
   :rtype: None

   """
   score_list = getPopScores(population, fitness)
   pylab.plot(score_list, 'o')
   pylab.title("Plot of population score distribution")
   pylab.xlabel('Individual')
   pylab.ylabel('Score')
   pylab.grid(True)
   pylab.show()

# -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plotHistPopScore(population, fitness=False):
   """ Population score distribution histogram

   Example:
      >>> Interaction.plotHistPopScore(population)

   :param population: population object (:class:`GPopulation.GPopulation`)
   :param fitness: if True, the fitness score will be used, otherwise, the raw.
   :rtype: None

   """
   score_list = getPopScores(population, fitness)
   n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1)
   pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--')
   pylab.xlabel('Score')
   pylab.ylabel('Frequency')
   pylab.grid(True)
   pylab.title("Plot of population score distribution")
   pylab.show()

# -----------------------------------------------------------------
项目:dynamic-walking    作者:stephane-caron    | 项目源码 | 文件源码
def plot_profiles(self):
        """
        Plot TOPP profiles, e.g. for debugging.
        """
        import pylab
        pylab.ion()
        self.topp.WriteProfilesList()
        self.topp.WriteSwitchPointsList()
        profileslist = TOPP.TOPPpy.ProfilesFromString(
            self.topp.resprofilesliststring)
        switchpointslist = TOPP.TOPPpy.SwitchPointsFromString(
            self.topp.switchpointsliststring)
        TOPP.TOPPpy.PlotProfiles(profileslist, switchpointslist)
        TOPP.TOPPpy.PlotAlphaBeta(self.topp)
        pylab.title("%s phase profile" % type(self).__name__)
        pylab.axis([0, 1, 0, 10])
项目:HousePrices    作者:MizioAnd    | 项目源码 | 文件源码
def predicted_vs_actual_sale_price(self, x_train, y_train, title_name):
        # Split the training data into an extra set of test
        x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        lasso = LassoCV(alphas=[0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1,
                                0.3, 0.6, 1],
                        max_iter=50000, cv=10)
        # lasso = RidgeCV(alphas=[0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1,
        #                         0.3, 0.6, 1], cv=10)

        lasso.fit(x_train_split, y_train_split)
        y_predicted = lasso.predict(X=x_test_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual Sale Price')
        plt.ylabel('Predicted Sale Price')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
项目:HousePrices    作者:MizioAnd    | 项目源码 | 文件源码
def predicted_vs_actual_sale_price_xgb(self, xgb_params, x_train, y_train, seed, title_name):
        # Split the training data into an extra set of test
        x_train_split, x_test_split, y_train_split, y_test_split = train_test_split(x_train, y_train)
        dtrain_split = xgb.DMatrix(x_train_split, label=y_train_split)
        dtest_split = xgb.DMatrix(x_test_split)

        res = xgb.cv(xgb_params, dtrain_split, num_boost_round=1000, nfold=4, seed=seed, stratified=False,
                     early_stopping_rounds=25, verbose_eval=10, show_stdv=True)

        best_nrounds = res.shape[0] - 1
        print(np.shape(x_train_split), np.shape(x_test_split), np.shape(y_train_split), np.shape(y_test_split))
        gbdt = xgb.train(xgb_params, dtrain_split, best_nrounds)
        y_predicted = gbdt.predict(dtest_split)
        plt.figure(figsize=(10, 5))
        plt.scatter(y_test_split, y_predicted, s=20)
        rmse_pred_vs_actual = self.rmse(y_predicted, y_test_split)
        plt.title(''.join([title_name, ', Predicted vs. Actual.', ' rmse = ', str(rmse_pred_vs_actual)]))
        plt.xlabel('Actual Sale Price')
        plt.ylabel('Predicted Sale Price')
        plt.plot([min(y_test_split), max(y_test_split)], [min(y_test_split), max(y_test_split)])
        plt.tight_layout()
项目:sentisignal    作者:jonathanmanfield    | 项目源码 | 文件源码
def check_acf(df):
    df_num = df.select_dtypes(include=[np.float, np.int])
    for index in df_num.columns:
        plt.figure(figsize=(8,10))
        if index in ['LOG_BULL_RETURN', 'LOG_BEAR_RETURN','RTISf', 'TOTAL_SCANNED_MESSAGES_DIFF', 'TOTAL_SENTIMENT_MESSAGES_DIFF']:
            fig = sm.graphics.tsa.plot_acf(df_num[index][1:],lags=40)
            plt.title(index)
        elif index in ['LOG_BULL_BEAR_RATIO']:
            fig = sm.graphics.tsa.plot_acf(df_num[index][2:],lags=40)
            plt.title(index)
        else: 
            fig = sm.graphics.tsa.plot_acf(df_num[index],lags=40)
            plt.title(index)
    return fig

# check adf test
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t1, self.n_A1, 'b--', label='A1: Time Step = 0.05')
        pl.plot(self.t1, self.n_B1, 'b', label='B1: Time Step = 0.05')
        pl.plot(self.t2, self.n_A2, 'g--', label='A2: Time Step = 0.1')
        pl.plot(self.t2, self.n_B2, 'g', label='B2: Time Step = 0.1')
        pl.plot(self.t1, self.n_A1_true, 'r--', label='True A1: Time Step = 0.05')
        pl.plot(self.t1, self.n_B1_true, 'r', label='True B1: Time Step = 0.05')
        pl.plot(self.t2, self.n_A2_true, 'c--', label='True A2: Time Step = 0.1')
        pl.plot(self.t2, self.n_B2_true, 'c', label='True B2: Time Step = 0.1')
        pl.title('Double Decay Probelm-Approximation Compared with True in Defferent Time Steps')
        pl.xlim(0.0, 0.1)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True, fontsize='small')
        pl.grid(True)
        pl.savefig("computational_physics homework 4(improved-7).png")
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show(self):
#        pl.semilogy(self.theta, self.omega)
#                , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D)
        pl.plot(self.theta_phase ,self.omega_phase, '.', label = '$t \\approx 2\\pi n / \\Omega_D$')
        pl.xlabel('$\\theta$ (radians)')
        pl.ylabel('$\\omega$ (radians/s)')
        pl.legend()
#        pl.text(-1.4, 0.3, '$\\omega$ versus $\\theta$ $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
#        pl.show()
#        pl.semilogy(self.time_array, self.delta)
#        pl.legend(loc = 'upper center', fontsize = 'small')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta (radians)$')
#        pl.xlim(0, self.T)
#        pl.ylim(float(input('ylim-: ')),float(input('ylim+: ')))
#        pl.ylim(1E-11, 0.01)
#        pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method')
#        pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$')
#        pl.title('Simple Harmonic Motion')
        pl.title('Chaotic Regime')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_log(self):
#        pl.subplot(121)
        pl.semilogy(self.time_array, self.delta, 'c')
        pl.xlabel('$time (s)$')
        pl.ylabel('$\\Delta\\theta$ (radians)')
        pl.xlim(0, self.T)
#        pl.ylim(1E-11, 0.01)
        pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
        pl.show()

#    def show_log_sub122(self):
#        pl.subplot(122)
#        pl.semilogy(self.time_array, self.delta, 'g')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta$ (radians)')
#        pl.xlim(0, self.T)
#        pl.ylim(1E-6, 100)
#        pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
#        pl.title('Chaotic Regime')
#        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_log(self):
#        pl.subplot(121)
        pl.semilogy(self.time_array, self.delta, 'c')
        pl.xlabel('$time (s)$')
        pl.ylabel('$\\Delta\\theta$ (radians)')
        pl.xlim(0, self.T)
#        pl.ylim(1E-11, 0.01)
        pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
        pl.show()

#    def show_log_sub122(self):
#        pl.subplot(122)
#        pl.semilogy(self.time_array, self.delta, 'g')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta$ (radians)')
#        pl.xlim(0, self.T)
#        pl.ylim(1E-6, 100)
#        pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
#        pl.title('Chaotic Regime')
#        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_complex(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 16,
        }
        pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font)
        pl.plot(self.x, self.y, label = '$v_0 = %.5f m/s$'%self.v0 + ', ' + '$\\theta = %.4f \degree$'%self.theta)
        pl.xlabel('x $m$')
        pl.ylabel('y $m$')
        pl.xlim(0, 300)
        pl.ylim(-100, 20)
        pl.grid()
        pl.legend(loc = 'upper right', shadow = True, fontsize = 'small')
        pl.text(15, -90, 'scan to approach the minimum velocity and corresponding launching angle', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_simple(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 16,
        }
        pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font)
        pl.plot(self.x, self.y, label ='$\\alpha = %.0f \degree$'%self.alpha)
        pl.xlabel('x $m$')
        pl.ylabel('y $m$')
        pl.xlim(0, 400)
        pl.ylim(-100, 200)
        pl.grid()
        pl.legend(loc = 'upper right', shadow = True, fontsize = 'medium')
        pl.text(5, -80, 'trojectories varing with angles of wind', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 14,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(41, 16, 'Only with air drag', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 12,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(34, 16, '       With both air drag and \n reduced air density-isothermal', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 12,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(34.5, 16, '       With both air drag and \n reduced air density-adiabatic', fontdict = font)
        pl.show()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def DrawDvs(pl, closes, curve, sign, dvs, pandl, sh, title, leag=None, lad=None ):
    pl.figure
    pl.subplot(311)
    pl.title("id:%s Sharpe ratio: %.2f"%(str(title),sh))
    pl.plot(closes)
    DrawLine(pl, sign, closes)
    pl.subplot(312)
    pl.grid()
    if dvs != None:
        pl.plot(dvs)
    if isinstance(curve, np.ndarray):
        DrawZZ(pl, curve, 'r')
    if leag != None:
        pl.plot(leag, 'r')
    if lad != None:
        pl.plot(lad, 'b')
    #pl.plot(stock.GuiYiHua(closes[:i])[60:])
    pl.subplot(313)
    pl.plot(sign)
    pl.plot(pandl)
    pl.show()
    pl.close()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def TradeResult_Boll(pl, bars, trade_positions, zhijin,changwei, title=''):
    """??????
    bars: df ???  c????
    trade_positions: np.darray or df ????
    zhijin: df index?bars
    changwei: df index?bars
    title: str ??????decode(utf8)
    """

    signals = pd.DataFrame(index=bars.index)
    signals['signal'] = 0.0
    signals['signal'] = np.zeros(len(bars['c']))
    if agl.IsNone(trade_positions):
        signals['positions'] = signals['signal'].diff()  
        signals['positions'][10] = 1
        signals['positions'][13] = 1
        signals['positions'][20] = -1
    else:
        signals['positions'] = trade_positions
    ShowTradeResult2(pl, bars, signals, zhijin,changwei , 0, title=title)
项目:pysynphot    作者:spacetelescope    | 项目源码 | 文件源码
def plotdata(obsmode,spectrum,val,odict,sdict,
             instr,fieldname,outdir,outname):
    isetting=P.isinteractive()
    P.ioff()

    P.clf()
    P.plot(obsmode,val,'.')
    P.ylabel('(pysyn-syn)/syn')
    P.xlabel('obsmode')
    P.title("%s: %s"%(instr,fieldname))
    P.savefig(os.path.join(outdir,outname+'_obsmode.ps'))

    P.clf()
    P.plot(spectrum,val,'.')
    P.ylabel('(pysyn-syn)/syn')
    P.xlabel('spectrum')
    P.title("%s: %s"%(instr,fieldname))
    P.savefig(os.path.join(outdir,outname+'_spectrum.ps'))

    matplotlib.interactive(isetting)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def starPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
    """Star bin plot"""

    mag_g = data[mag_g_dred_flag]
    mag_r = data[mag_r_dred_flag]

    filter = star_filter(data)

    iso_filter = (iso.separation(mag_g, mag_r) < 0.1)

    # projection of image
    proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
    x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC'])

    plt.scatter(x, y, edgecolor='none', s=3, c='black')
    plt.xlim(0.2, -0.2)
    plt.ylim(-0.2, 0.2)
    plt.gca().set_aspect('equal')
    plt.xlabel(r'$\Delta \alpha$ (deg)')
    plt.ylabel(r'$\Delta \delta$ (deg)')

    plt.title('Stars')
项目:fang    作者:rgrosse    | 项目源码 | 文件源码
def show_particles(rbm, state, dataset, display=True, figname='PCD particles', figtitle='PCD particles',
                   size=None):
    try:
        fantasy_vis = rbm.vis_expectations(state.h)
    except:
        fantasy_vis = state

    if size is None:
        size = (dataset.num_rows, dataset.num_cols)
    imgs = [fantasy_vis[j, :np.prod(size)].reshape(size).as_numpy_array()
            for j in range(fantasy_vis.shape[0])]
    visual = misc.norm01(misc.pack(imgs))
    if display:
        pylab.figure(figname)
        pylab.matshow(visual, cmap='gray', fignum=False)
        pylab.title(figtitle)
    return visual
项目:fang    作者:rgrosse    | 项目源码 | 文件源码
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True,
                figname='Gibbs chains', figtitle='Gibbs chains'):
    samples = gnp.zeros((num_particles, num_samples, state.v.shape[1]))
    state = state[:num_particles, :, :]

    for i in range(num_samples):
        samples[:, i, :] = rbm.vis_expectations(state.h)

        for j in range(show_every):
            state = rbm.step(state)

    npix = dataset.num_rows * dataset.num_cols
    rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array()
                      for j in range(num_samples)],
                     normalize=False)
            for i in range(num_particles)]
    grid = vm.vjoin(rows, normalize=False)

    if display:
        pylab.figure(figname)
        pylab.matshow(grid, cmap='gray', fignum=False)
        pylab.title(figtitle)
        pylab.gcf().canvas.draw()

    return grid
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:actinf    作者:x75    | 项目源码 | 文件源码
def plotstuff():
    X__ = np.load("tm_X.npy")
    S_pred = np.load("tm_S_pred.npy")
    E_pred = np.load("tm_E_pred.npy")
    M = np.load("tm_M.npy")

    pl.ioff()
    pl.suptitle("mode: %s (X: FM input, state pred: FM output)" % ("bluib"))
    pl.subplot(511)
    pl.title("X[goals]")
    pl.plot(X__[10:,0:4], "-x")
    pl.subplot(512)
    pl.title("X[prediction error]")
    pl.plot(X__[10:,4:], "-x")
    pl.subplot(513)
    pl.title("state pred")
    pl.plot(S_pred)
    pl.subplot(514)
    pl.title("error state - goal")
    pl.plot(E_pred)
    pl.subplot(515)
    pl.title("state")
    pl.plot(M)
    pl.show()
项目:actinf    作者:x75    | 项目源码 | 文件源码
def rh_model_plot(self):
        """prepare and plot model outputs over input variations from sweep"""
        assert hasattr(self, "X_model_sweep")
        assert hasattr(self, "Y_model_sweep")

        print "%s.rh_plot_model sweepsteps = %d" % (self.__class__.__name__, self.X_model_sweep.shape[0])
        print "%s.rh_plot_model environment = %s" % (self.__class__.__name__, self.environment)
        print "%s.rh_plot_model environment proprio dims = %d" % (self.__class__.__name__, self.environment.conf.m_ndims)

        # scatter_data_raw   = np.hstack((self.X_model_sweep[:,1:], self.Y_model_sweep))
        # scatter_data_cols  = ["X%d" % i for i in range(1, self.X_model_sweep.shape[1])]
        # scatter_data_cols += ["Y%d" % i for i in range(self.Y_model_sweep.shape[1])]
        # print "scatter_data_raw", scatter_data_raw.shape
        # # df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
        # df = pd.DataFrame(scatter_data_raw, columns=scatter_data_cols)

        title = "%s, input/output sweep of model %s at time %d" % (self.mode, self.model, -1)

        # plot_scattermatrix(df)
        # plot_scattermatrix_reduced(df)
        plot_colormeshmatrix_reduced(self.X_model_sweep, self.Y_model_sweep, ymin = -1.0, ymax = 1.0, title = title)

    ################################################################################
项目:actinf    作者:x75    | 项目源码 | 文件源码
def plot_scattermatrix(df, title = "plot_scattermatrix"):
    """plot a scattermatrix of dataframe df"""
    if df is None:
        print "plot_scattermatrix: no data passed"
        return

    from pandas.tools.plotting import scatter_matrix
    # df = pd.DataFrame(X, columns=['x1_t', 'x2_t', 'x1_tptau', 'x2_tptau', 'u_t'])
    # scatter_data_raw = np.hstack((np.array(Xs), np.array(Ys)))
    # scatter_data_raw = np.hstack((Xs, Ys))
    # print "scatter_data_raw", scatter_data_raw.shape

    pl.ioff()
    # df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
    sm = scatter_matrix(df, alpha=0.2, figsize=(10, 10), diagonal='hist')
    fig = sm[0,0].get_figure()
    fig.suptitle(title)
    if SAVEPLOTS:
        fig.savefig("fig_%03d_scattermatrix.pdf" % (fig.number), dpi=300)
    fig.show()
    # pl.show()
项目:ArduPi-ECG    作者:ferdavid1    | 项目源码 | 文件源码
def main():
    data = pd.read_table('../Real_Values.txt').get_values()
    x = [float(d) for d in data]
    test = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860])
    n_predict = 100
    extrapolation = fourierExtrapolation(x, n_predict)

    pl.figure()
    pl.plot(np.arange(len(x), len(extrapolation) + len(x)), extrapolation, 'r', label = 'extrapolation')
    pl.plot(x, 'b', label = 'Given Data', linewidth = 3)
    pl.legend()
    pl.ylabel('BPM')
    pl.xlabel('Sample')
    pl.title('Fourier Extrapolation')
    pl.savefig('FourierExtrapolation.png')
    #pl.show()
    with open('Fourier_PredValues.txt', 'w') as out:
        out.write(str([e for e in extrapolation]).strip('[]'))
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
    """ Plot multiples ROC curves as separate at the same painting area. """
    pylab.clf()
    pylab.title(title)
    for ix, r in enumerate(rocList):
        ax = pylab.subplot(4,4,ix+1)
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')

        if not labels:
            labels = ['' for x in rocList]

        pylab.text(0.2,0.1,labels[ix],fontsize=8)
        pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)

    pylab.show()
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot(self,title='',include_baseline=False,equal_aspect=True):
        """ Method that generates a plot of the ROC curve
            Parameters:
                title: Title of the chart
                include_baseline: Add the baseline plot line if it's True
                equal_aspect: Aspects to be equal for all plot
        """

        pylab.clf()
        pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
        if include_baseline:
            pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        pylab.xticks(pylab.arange(0,1.1,.1))
        pylab.yticks(pylab.arange(0,1.1,.1))
        pylab.grid(True)
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')
        pylab.xlabel('1 - Specificity')
        pylab.ylabel('Sensitivity')
        pylab.title(title)

        pylab.show()
项目:mglex    作者:fungs    | 项目源码 | 文件源码
def plot_clusters_pca(responsibilities, color_groups):
    from sklearn.decomposition import RandomizedPCA
    import pylab as pl
    from random import shuffle

    colors = list(colors_dict.values())
    shuffle(colors)

    pca = RandomizedPCA(n_components=2)
    X = pca.fit_transform(responsibilities)
    # print >>stderr, pca.explained_variance_ratio_

    pl.figure()
    pl.scatter(X[:, 0], X[:, 1], c="grey", label="unknown")
    for c, sub, i in zip(colors, color_groups, count(0)):
        pl.scatter(X[sub, 0], X[sub, 1], c=c, label=str(i))
    pl.legend()
    pl.title("PCA responsibility matrix")
    pl.show()
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def plot(func):
    random_state = check_random_state(0)
    one_core = []
    multi_core = []
    sample_sizes = range(1000, 6000, 1000)

    for n_samples in sample_sizes:
        X = random_state.rand(n_samples, 300)

        start = time.time()
        func(X, n_jobs=1)
        one_core.append(time.time() - start)

        start = time.time()
        func(X, n_jobs=-1)
        multi_core.append(time.time() - start)

    pl.figure('scikit-learn parallel %s benchmark results' % func.__name__)
    pl.plot(sample_sizes, one_core, label="one core")
    pl.plot(sample_sizes, multi_core, label="multi core")
    pl.xlabel('n_samples')
    pl.ylabel('Time (s)')
    pl.title('Parallel %s' % func.__name__)
    pl.legend()
项目:Oedipus    作者:tum-i22    | 项目源码 | 文件源码
def plotAccuracyGraph(X, Y, Xlabel='Variable', Ylabel='Accuracy', graphTitle="Test Accuracy Graph", filename="graph.pdf"):
    """ Plots and saves accuracy graphs """
    try:
        timestamp = int(time.time())
        fig = P.figure(figsize=(8,5))
        # Set the graph's title
        P.title(graphTitle, fontname='monospace')
        # Set the axes labels
        P.xlabel(Xlabel, fontsize=12, fontname='monospace')
        P.ylabel(Ylabel, fontsize=12, fontname='monospace')
        # Add horizontal and vertical lines to the graph
        P.grid(color='DarkGray', linestyle='--', linewidth=0.1, axis='both')
        # Add the data to the graph
        P.plot(X, Y, 'r-*', linewidth=1.0)
        # Save figure
        prettyPrint("Saving figure to ./%s" % filename)#(graphTitle.replace(" ","_"), timestamp))
        P.tight_layout()
        fig.savefig("./%s" % filename)#(graphTitle.replace(" ", "_"), timestamp))

    except Exception as e:
        prettyPrint("Error encountered in \"plotAccuracyGraph\": %s" % e, "error")
        return False

    return True
项目:MIT-CS-lectures    作者:William-Python-King    | 项目源码 | 文件源码
def ansQuest(maxTime,numTrials):
    means=[]
    distLists=performSim(maxTime,numTrials)
    for t in range(maxTime+1):
        tot=0.0
        for distL  in  distLists:
            tot+=distL[t]
        means.append(tot/len(distL))
    pylab.figure()
    pylab.plot(means)
    pylab.xlabel('distance')
    pylab.ylabel('time')
    pylab.title('Average Distance  vs. Time ('+str(len(distLists))+'trials)')
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
    # Receptive Fields Summary
    try:
        W = layer.W
    except:
        W = layer
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) 
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

    fig = mpl.figure(figOffset); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,np.shape(fields)[0]):
        im = grid[i].imshow(fields[i],cmap=cmap); 

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    # 
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    try:
        W = layer.output
    except:
        W = layer
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf(); 

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
    # Receptive Fields Summary
    W = layer.W
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    fieldsN = min(fields.shape[0],maxFields)
    perRow = int(math.floor(math.sqrt(fieldsN)))
    perColumn = int(math.ceil(fieldsN/float(perRow)))

    fig = mpl.figure(figName); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,fieldsN):
        im = grid[i].imshow(fields[i],cmap=cmap);

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    #
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    W = layer.output
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf();

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();