Python matplotlib.pyplot 模块,ion() 实例源码

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

项目:keras-utilities    作者:cbaziotis    | 项目源码 | 文件源码
def on_train_begin(self, logs={}):
        sns.set_style("whitegrid")
        sns.set_style("whitegrid", {"grid.linewidth": 0.5,
                                    "lines.linewidth": 0.5,
                                    "axes.linewidth": 0.5})
        flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e",
                  "#2ecc71"]
        sns.set_palette(sns.color_palette(flatui))
        # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
        # sns.set_palette(sns.color_palette("Set2", 10))

        plt.ion()  # set plot to animated
        self.fig = plt.figure(
            figsize=(self.width * (1 + len(self.get_metrics(logs))),
                     self.height))  # width, height in inches

        # move it to the upper left corner
        move_figure(self.fig, 25, 25)
项目:keras-utilities    作者:cbaziotis    | 项目源码 | 文件源码
def on_train_begin(self, logs={}):
        for layer in self.get_trainable_layers():
            for param in self.parameters:
                if any(w for w in layer.weights if param in w.name.split("_")):
                    name = layer.name + "_" + param
                    self.layers_stats[name]["values"] = numpy.asarray(
                        []).ravel()
                    for s in self.stats:
                        self.layers_stats[name][s] = []

        # plt.style.use('ggplot')
        plt.ion()  # set plot to animated
        width = 3 * (1 + len(self.stats))
        height = 2 * len(self.layers_stats)
        self.fig = plt.figure(
            figsize=(width, height))  # width, height in inches
        # sns.set_style("whitegrid")
        # self.draw_plot()
项目:multimodal_varinf    作者:tmoer    | 项目源码 | 文件源码
def __init__(self,to_plot = True):
        self.state = np.array([0,0])        
        self.observation_shape = np.shape(self.get_state())[0]

        if to_plot:
            plt.ion()
            fig = plt.figure()
            ax1 = fig.add_subplot(111,aspect='equal')
            #ax1.axis('off')
            plt.xlim([-0.5,5.5])
            plt.ylim([-0.5,5.5])

            self.g1 = ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red'))
            self.fig = fig
            self.ax1 = ax1
            self.fig.canvas.draw()
            self.fig.canvas.flush_events()
项目:learning-to-see-by-moving    作者:pulkitag    | 项目源码 | 文件源码
def vis_lmdb(prms, setName='train'):
    db  = mpio.DbReader(prms['paths']['lmdb'][setName])
    plt.ion()
    fig = plt.figure() 
    ax  = plt.subplot(1,1,1)
    clNames = get_classnames(prms)
    N = 100
    for i in range(N):
        im,lb = db.read_next()
        im    = im.transpose((1,2,0))
        im    = im[:,:,[2,1,0]]
        ax.imshow(im)
        ax.axis('off')
        plt.title('Class: %s' % clNames[lb])        
        raw_input() 

##
# Make all the lmdbs
项目:usbtc08    作者:bankrasrg    | 项目源码 | 文件源码
def init_plot(self):
        # Interactive mode
        plt.ion()
        # Chart size and margins
        plt.figure(figsize = (20, 10))
        plt.subplots_adjust(hspace = 0.05, top = 0.95, bottom = 0.1, left = 0.05, right = 0.95)
        # Setup axis labels and ranges
        plt.title('Pico Technology TC-08')
        plt.xlabel('Time [s]')
        plt.ylabel('Temperature [' + self.unit_text + ']')
        plt.xlim(0, self.duration)
        self.plotrangemin = 19
        self.plotrangemax = 21
        plt.ylim(self.plotrangemin, self.plotrangemax)
        # Enable a chart line for each channel
        self.lines = []
        for i in CHANNEL_CONFIG:
            if CHANNEL_CONFIG.get(i) != ' ':
                self.lines.append(line(plt, CHANNEL_NAME.get(i)))
            else:
                self.lines.append(line(plt, 'Channel {:d} OFF'.format(i)))
        # Plot the legend
        plt.legend(loc = 'best', fancybox = True, framealpha = 0.5)
        plt.draw()
项目:pyrealtime    作者:ewhitmire    | 项目源码 | 文件源码
def initialize(self):
        self.fig = plt.figure()
        self.axes_dict = self.create_fig(self.fig)

        for plot_key in self.plot_layers.keys():
            plot_layer = self.plot_layers[plot_key]
            if plot_key not in self.axes_dict:
                raise KeyError("No axis created for plot %s" % plot_key)
            plot_layer.create_fig(self.fig, self.axes_dict[plot_key])

        # matplotlib.animation.Animation._blit_draw = _blit_draw
        self.anim = animation.FuncAnimation(self.fig, self.update_func, init_func=self.init_func, frames=None,
                                      interval=1000 / self.fps, blit=True)
        print("show")
        plt.ion()
        plt.show()
        print("continue")
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spikepattern(spike_trains, sim_time):
    """Plot set of spike trains (spike pattern)"""
    plt.ioff()

    plt.figure()
    for i in xrange(len(spike_trains)):
        spike_times = spike_trains[i].value
        plt.plot(spike_times, np.full(len(spike_times), i,
                 dtype=np.int), 'k.')
    plt.xlim((0.0, sim_time))
    plt.ylim((0, len(spike_trains)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Neuron index')
    plt.show()

    plt.ion()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spiker(record, spike_trains_target, neuron_index=0):
    """Plot spikeraster and target timings for given neuron index"""
    plt.ioff()

    spike_trains = [np.array(i.spiketrains[neuron_index])
                    for i in record.segments]
    n_segments = record.size['segments']

    plt.figure()
    for i in xrange(len(spike_trains)):
        plt.plot(spike_trains[i], np.full(len(spike_trains[i]), i + 1,
                 dtype=np.int), 'k.')
    target_timings = spike_trains_target[neuron_index].value
    plt.plot(target_timings, np.full(len(target_timings), 1.025 * n_segments),
             'kx', markersize=8, markeredgewidth=2)
    plt.xlim((0., np.float(record.segments[0].t_stop)))
    plt.ylim((0, np.int(1.05 * n_segments)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Trials')
    plt.title('Output neuron {}'.format(neuron_index))
    plt.show()

    plt.ion()
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def setup_plot_iv_multi(self,nrows=16,ncols=8,xwin=True):
    if not isinstance(self.vbias,np.ndarray): self.vbias=make_Vbias()
    ttl=str('QUBIC I-V curves (%s)' % (self.obsdate.strftime('%Y-%b-%d %H:%M UTC')))

    nbad=0
    for val in self.is_good_iv():
        if not val:nbad+=1
    ttl+=str('\n%i flagged as bad pixels' % nbad)

    if xwin: plt.ion()
    else: plt.ioff()
    fig,axes=plt.subplots(nrows,ncols,sharex=True,sharey=False,figsize=self.figsize)
    if xwin: fig.canvas.set_window_title('plt: '+ttl)
    fig.suptitle(ttl,fontsize=16)
    plt.xlabel('Bias Voltage  /  V')
    plt.ylabel('Current  /  $\mu$A')
    return fig,axes
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def setup_plot_iv(self,TES,xwin=True):
    ttl=str('QUBIC I-V curve for TES#%3i (%s)' % (TES,self.obsdate.strftime('%Y-%b-%d %H:%M UTC')))
    if self.temperature==None:
        tempstr='unknown'
    else:
        tempstr=str('%.0f mK' % (1000*self.temperature))
    subttl=str('Array %s, ASIC #%i, Pixel #%i, Temperature %s' % (self.detector_name,self.asic,self.tes2pix(TES),tempstr))
    if xwin: plt.ion()
    else: plt.ioff()
    fig=plt.figure(figsize=self.figsize)
    fig.canvas.set_window_title('plt: '+ttl) 
    fig.suptitle(ttl+'\n'+subttl,fontsize=16)
    ax=plt.gca()
    ax.set_xlabel('Bias Voltage  /  V')
    ax.set_ylabel('Current  /  $\mu$A')
    ax.set_xlim([self.bias_factor*self.min_bias,self.bias_factor*self.max_bias])
    return fig,ax
项目:sendobox    作者:sendobox    | 项目源码 | 文件源码
def plot(api, images, aoi):
    # GeoJSON FeatureCollection containing footprints and properties of the scenes
    metadata = api.get_footprints()#images
    properties = [metadata.features[i].properties for i in range(0, len(images))]
    footprints = [metadata.features[i].geometry.coordinates for i in range(0,len(images))]

    # Get coordinates of the Area of Interest (AOI)
    with open(aoi) as geojson_file:
        geojson = json.load(geojson_file)
    for feature in geojson['features']:
        polygon = (feature['geometry'])
    aoi_coordinates = polygon['coordinates']
    aoi_x_coordinates = [aoi_coordinates[0][i][0] for i in range(0,len(aoi_coordinates[0]))]
    aoi_y_coordinates = [aoi_coordinates[0][i][1] for i in range(0,len(aoi_coordinates[0]))]

    plt.ion()

    # Plot Footprints and AOI
    for i in range(0,len(images)):
        plt.plot(*zip(*footprints[i][0]), label='Image '+str(properties[i]['product_id']), linestyle='dashed')
        plt.plot(aoi_x_coordinates, aoi_y_coordinates, 'r')
        plt.legend()

    plt.show()
项目:Fluid2d    作者:pvthinker    | 项目源码 | 文件源码
def create_fig(self):
        fig  = plt.figure(figsize=(16,6))
        ax1 = fig.add_subplot(1, 1, 1)
        ax1.cla()
        ax1.hold(True)

        self.time_str = 'time = %-6.2f'
        ax1.set_title( '' )
        ax1.set_xlabel('X')
        ax1.set_ylabel('Y')

        self.ax1 = ax1

        plt.ion()

        self.im=ax1.imshow( self.z2d, 
                       vmin=self.cax[0],vmax=self.cax[1],
                       cmap=plt.get_cmap('jet'),origin='lower',
                       interpolation='nearest')

        cb = plt.colorbar(self.im)

        fig.show()
        fig.canvas.draw()
        self.fig = fig
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def _render(self, mode = "human", close = False):
        if close:
            return

        import matplotlib.pyplot as plt

        if self.tick == 0:
            plt.ion()

        G = self.G
        attrs = nx.get_node_attributes(G, "ndd")
        values = ["red" if attrs[v] else "blue" for v in G.nodes()]

        plt.clf()
        nx.draw(G,
            pos = nx.circular_layout(G),
            node_color = values)
        plt.pause(0.01)

        return []
项目:strategy    作者:kanghua309    | 项目源码 | 文件源码
def _render(self, mode='human', close=False):
        if self.inited == False: return
        if self.render_on == 0:
            # self.fig = plt.figure(figsize=(10, 4))
            self.fig = plt.figure(figsize=(12, 6))
            self.render_on = 1
            plt.ion()

        plt.clf()
        self._plot_trades()
        plt.suptitle("Code: " + self.src.symbol + ' ' + \
                     "Round:" + str(self.reset_count) + "-" + \
                     "Step:" + str(self.src.idx - self.src.orgin_idx) + "  (" + \
                     "from:" + self.src.reset_start_day + " " + \
                     "to:" + self.src.reset_end_day + ")")
        plt.pause(0.001)
        return self.fig
项目:raspberrypi_tempmon    作者:gavinlyonsrepo    | 项目源码 | 文件源码
def graph_live_data(self):
        """draw a live graph of pi GPU """
        tempg = []
        plt.ion()

        #pre-load dummy data
        for i in range(0, 26):
            tempg.append(0)

        while True:
            #GPU
            ostemp = os.popen('vcgencmd measure_temp').readline()
            temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
            tempg.append(temp)
            tempg.pop(0)
            #plot graph pass function temp
            plot_now_func(tempg)
            plt.pause(1)
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def __init__(self, evaluator, figsize=(7, 7), sleep=0.0001):
        super(DataFittingMonitor, self).__init__(evaluator, 'data_fitting_monitor')
        self._sleep = sleep
        self._network = self.evaluator.network
        self._fig = plt.figure(figsize=figsize)
        self._ax = self._fig.add_subplot(111)

        self._scat = self._ax.scatter(
            [], [],
            label=r'$predicted$',
            c=self.color_test,      # blue like
            s=30, alpha=0.6, edgecolor='none')
        self._real_line, = self._ax.plot(
            [None, None], [None, None],
            ls='--', lw=3,
            c=self.color_train,        # red like
            label=r'$real$')
        self._ax.grid(True)
        self._ax.legend(loc='upper left')
        self._ax.set_xlabel(r'$Real\ data$')
        self._ax.set_ylabel(r'$Predicted$')

        plt.ion()
        plt.show()
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def __init__(self, grid_space, objects, evaluator, figsize, sleep=0.001):
        super(ScaleMonitor, self).__init__(evaluator, 'score_monitor')
        self._network = self.evaluator.network
        self._axes = {}
        self._tplot_axes = {}
        self._vplot_axes = {}
        self._fig = plt.figure(figsize=figsize)
        self._sleep = sleep
        for r_loc, name in enumerate(objects):
            r_span, c_span = 1, grid_space[1]
            self._axes[name] = plt.subplot2grid(grid_space, (r_loc, 0), colspan=c_span, rowspan=r_span)
            if name != objects[-1]:
                plt.setp(self._axes[name].get_xticklabels(), visible=False)
            self._axes[name].set_ylabel(r'$%s$' % name.replace(' ', r'\ ').capitalize())
        self._fig.subplots_adjust(hspace=0.1)
        plt.ion()
        plt.show()
项目:information-bottleneck    作者:djstrouse    | 项目源码 | 文件源码
def gen_blurred_diag_pxy(s):
    X = 1024
    Y = X

    # generate pdf
    from scipy.stats import multivariate_normal
    pxy = np.zeros((X,Y))
    rv = multivariate_normal(cov=s)
    for x in range(X):        
        pxy[x,:] = np.roll(rv.pdf(np.linspace(-X/2,X/2,X+1)[:-1]),int(X/2+x))
    pxy = pxy/np.sum(pxy)

    # plot p(x,y)
    import matplotlib.pyplot as plt
    plt.figure()
    plt.contourf(pxy)
    plt.ion()
    plt.title("p(x,y)")
    plt.show()

    return pxy
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def set_interactive(interactive = False):
    """This function does something.

    Args:
       name (str):  The name to use.

    Kwargs:
       state (bool): Current state to be in.

    Returns:
       int.  The return code::

          0 -- Success!
          1 -- No good.
          2 -- Try again.

    Raises:
       AttributeError, KeyError
     """
    if interactive:
        plt.ion()
    else:
        plt.ioff()
项目:a3c    作者:siemanko    | 项目源码 | 文件源码
def main():
    session = tf.Session()

    env = gym.make('Pong-v0')
    last_observation = env.reset()
    preproc_f = preproc_graph(session, env.observation_space.shape)

    fig, ax = plt.subplots(figsize=(6,6))
    plt.ion()

    for _ in range(1000):
        observation, _, _, _ = env.step(env.action_space.sample())
        print("wtf?")
        pp = preproc_f(last_observation, observation)
        print("wtf!")

        ax.imshow(pp[:,:,0])
        plt.pause(0.05)

        print("Let the bodies hit the floor")

        last_observation = observation
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def viewanim(data,start=0,skip=2,title=None,cmap='bone', ms_per_step=None):
    """
    Show an animation of a single simulation run, each node
    represented (via its node label) as pixel (i,j) in an MxN image.
    So this will only be useful for grid graphs.

    Args:
        data: MxNxT array of voltage traces
        start: first timestep to show
        skip: timesteps to advance in each frame (higher -> faster)
        title: figure title
        cmap: matplotlib colormap (name OR object)
    """
    #plt.ioff()
    anim = createanim(data,start,skip,title=title,cmap=cmap, ms_per_step=ms_per_step)
    plt.show()
    plt.ion()
项目:Simulator    作者:libsmelt    | 项目源码 | 文件源码
def draw_loop():
    """
    Draw the graph in a loop

    """
    global G

    plt.ion()

    # mng = plt.get_current_fig_manager()
    # mng.resize(*mng.window.maxsize())
    plt.draw()

    for line in fileinput.input():
        if output(line):
            plt.clf()
            nx.draw(G)
            plt.draw()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def _test_AsynDrawKline(self):
        code = '300033'
        start_day = '2017-8-25'
        #df = stock.getHisdatDataFrameFromRedis(code, start_day)
        df = stock.getFiveHisdatDf(code, start_day=start_day)
        import account
        account = account.LocalAcount(account.BackTesting())
        #????????
        indexs = agl.GenRandomArray(len(df), 3)
        trade_bSell = [0,1,0]
        df_trades = df[df.index.map(lambda x: x in df.index[indexs])]
        df_trades = df_trades.copy()
        df_trades[AsynDrawKline.enum.trade_bSell] = trade_bSell

        plt.ion()
        for i in range(10):
            AsynDrawKline.drawKline(df[i*10:], df_trades)

        plt.ioff()
        #plt.show()  #???????? ????????
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        if GRAPHICS:
            plt.ion()
            plt.show()

            xBottom = self.drawParams['xBottom']
            carlength = self.drawParams['carlength']
            ego = self.drawParams['ego']

            self.drawParams['txtDist'].set_text('distance: %f' % self.d)
            self.drawParams['txtS_ego'].set_text('ego speed: %f' % self.s_ego)
            self.drawParams['txtS_lead'].set_text(
                'lead speed: %f' % self.s_lead[self.tstep])

            self.ax.set_xlim(
                (min([-self.d - 2 * carlength, xBottom]), 2 * carlength))

            ego.set_xy((-self.d - carlength, 0))

            plt.draw()

            plt.pause(0.1)
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        plt.ion()
        plt.show()

        self.ax.cla()

        img = self.j.render(self.simparams, np.zeros(
            (500, 500)).astype('uint32'))
        #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        plt.draw()

        plt.pause(1e-6)

        return
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        # plt.ion()
        # plt.show()

        # self.ax.cla()

        # img = self.j.render(self.simparams, np.zeros((500,500)).astype('uint32'))
        # #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        # self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        # #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        # plt.draw()

        # plt.pause(1e-6)

        return
项目:RocketFuel    作者:CS236340    | 项目源码 | 文件源码
def __init__(self,ASN):
        self.filename = str(ASN) + 'network graph'
        self.alias_filename = str(ASN) + 'alias_candidates.txt'
        self.ISP_Network = networkx.Graph()
        self.files_read = 0
        self.border_points = set()
        if os.path.isfile(self.filename):
            load_file = shelve.open(self.filename, 'r')
            self.files_read = load_file['files_read']
            self.ISP_Network = load_file['ISP_Network']
            self.border_points = load_file['border_points']
        self.ASN = ASN
        plt.ion()
        country = raw_input('enter country to focus on map [Israel/Usa/Australia/other]: ')
        if country == 'Israel' or country == 'israel' or country == 'ISRAEL':
            self.wmap = Basemap(projection='aeqd', lat_0 = 31.4, lon_0 = 35, width = 200000, height = 450000, resolution = 'i')
        elif country == 'USA' or country == 'usa':
            self.wmap = Basemap(projection='aeqd', lat_0 = 40, lon_0 = -98, width = 4500000, height = 2700000, resolution = 'i')
        elif country == 'Australia' or 'australia' or 'AUSTRALIA':
            self.wmap = Basemap(projection='aeqd', lat_0 = -23.07, lon_0 = 132.08, width = 4500000, height = 3500000, resolution = 'i')
        else:
            self.wmap = Basemap(projection='cyl', resolution = 'c')
        plt.hold(False)
项目:TA_example_labs    作者:mit-racecar    | 项目源码 | 文件源码
def initialize(self):
        plt.ion()
        #Set up plot
        self.fig = plt.figure(figsize=plt.figaspect(2.))

        self.ax0 = self.fig.add_subplot(2,1,1)

        self.laser_angular, = self.ax0.plot([],[], 'r.')
        self.laser_filtered, = self.ax0.plot([],[], 'b-')

        self.ax0.set_ylim(-1, 15)
        self.ax0.set_xlim(-np.pi, +np.pi)
        self.ax0.invert_xaxis()
        self.ax0.grid()

        self.ax1 = self.fig.add_subplot(2,1,2) 
        self.ax1.invert_xaxis()
        self.ax1.grid()
        self.laser_euclid, = self.ax1.plot([],[], '.')
        self.laser_regressed, = self.ax1.plot([],[], 'g')

        self.redraw()
项目:infusion    作者:jiamings    | 项目源码 | 文件源码
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 64
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 1093
            self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20)
项目:infusion    作者:jiamings    | 项目源码 | 文件源码
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 128
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 545
            #self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                bz = self.sess.run(self.rand_init, feed_dict={self.x: bx, self.alpha: alpha})
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha, self.init: bz})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
            self.visualize(alpha=0.0, batch_size=10, repeat=2)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20, repeat=2)
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        raw_input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def stochastic_gradient_descent(self, f, x0, fprime, maxiter, args):
        import matplotlib.pyplot as plt
        input, targets = args
        stochastic_indices = np.random.permutation(maxiter)
        for i,index in enumerate(stochastic_indices):
            sys.stdout.write("Iteration | %d\r" % (i))
            sys.stdout.flush()
            if i % 10 == 0:
                plt.clf()
                plt.ion()
                #try:
                #    cost, grad = self.costFunction(x0, input[:,:index], targets[:index])
                #except, ValueError:
                cost, grad = self.costFunction(x0, input, targets)
                costs.append(cost)
                iters.append(i)
                plt.plot(iters, costs)
                plt.draw()
            # only pass a single training example for each iteration
            costGrad = fprime(x0, input[:,index][:,np.newaxis], targets[:,index][:,np.newaxis])
            x0 = x0 - self._ALPHA*costGrad
        return x0
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        raw_input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        raw_input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def stochastic_gradient_descent(self, f, x0, fprime, maxiter, args):
        import matplotlib.pyplot as plt
        input, targets = args
        stochastic_indices = np.random.permutation(maxiter)
        for i,index in enumerate(stochastic_indices):
            sys.stdout.write("Iteration | %d\r" % (i))
            sys.stdout.flush()
            if i % 10 == 0:
                plt.clf()
                plt.ion()
                #try:
                #    cost, grad = self.costFunction(x0, input[:,:index], targets[:index])
                #except, ValueError:
                cost, grad = self.costFunction(x0, input, targets)
                costs.append(cost)
                iters.append(i)
                plt.plot(iters, costs)
                plt.draw()
            # only pass a single training example for each iteration
            costGrad = fprime(x0, input[:,index][:,np.newaxis], targets[:,index][:,np.newaxis])
            x0 = x0 - self._ALPHA*costGrad
        return x0
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def stochastic_gradient_descent(self, f, x0, fprime, maxiter, args):
        import matplotlib.pyplot as plt
        input, targets = args
        stochastic_indices = np.random.permutation(maxiter)
        for i,index in enumerate(stochastic_indices):
            sys.stdout.write("Iteration | %d\r" % (i))
            sys.stdout.flush()
            if i % 10 == 0:
                plt.clf()
                plt.ion()
                #try:
                #    cost, grad = self.costFunction(x0, input[:,:index], targets[:index])
                #except, ValueError:
                cost, grad = self.costFunction(x0, input, targets)
                costs.append(cost)
                iters.append(i)
                plt.plot(iters, costs)
                plt.draw()
            # only pass a single training example for each iteration
            costGrad = fprime(x0, input[:,index][:,np.newaxis], targets[:,index][:,np.newaxis])
            x0 = x0 - self._ALPHA*costGrad
        return x0
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        raw_input("Program paused. Press enter to continue.")
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseLearnedFeatures(self):
        """
            Visualise the features learned by the autoencoder
        """
        import matplotlib.pyplot as plt

        extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture
        # number of rows and columns to plot (number of hidden units also stored in self._architecture)
        plotDims = np.rint(np.sqrt(self._architecture[1]))
        plt.ion()
        fig = plt.figure()
        plt.set_cmap("gnuplot")
        plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1)
        learnedFeatures = self.getLearnedFeatures()
        for i in range(self._architecture[1]):
            image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000
            ax = fig.add_subplot(plotDims, plotDims, i)
            plt.axis("off")
            ax.imshow(image, interpolation="nearest")
        plt.show()
        raw_input("Program paused. Press enter to continue.")
项目:rnn-tutorial-curve-predict    作者:timctho    | 项目源码 | 文件源码
def create_curve():
    # Create the curve which we want the RNN to learn
    plt.ion()
    fig = plt.figure(figsize=(10, 10))
    ax = plt.gca()
    r = np.arange(0, .34, 0.001)
    n_points = len(r)
    theta = 45 * np.pi * r
    x_offset, y_offset = .5, .5
    y_curve_points = 1.4 * r * np.sin(theta) + y_offset
    x_curve_points = r * np.cos(theta) + x_offset
    curve = list(zip(x_curve_points, y_curve_points))
    collection = LineCollection([curve], colors='k')
    ax.add_collection(collection)
    return ax, n_points, x_curve_points, y_curve_points
项目:US-image-prediction    作者:ChengruiWu008    | 项目源码 | 文件源码
def train_op(LR=0.0001,train_size=TRAINSIZE):
    sess = tf.Session()
    init = tf.global_variables_initializer()
    sess.run(init)
    train_op=tf.train.AdamOptimizer(LR).minimize(regretion_loss)
    xs,ys = get_next_batch()
    feed_dict={ x_RNN : xs,y_: ys}

    # plt.ion()
    # plt.show()
    for i in range(train_size):
        if i%10==0:
            loss= sess.run(regretion_loss,feed_dict=feed_dict)
            print('batch ' ,i , ' loss= ' , loss)
            f, a = plt.subplots(2, 1)
            # a[0][1].imshow(np.reshape(image_p[-1], (LONGITUDE, WIDTH)))
            # a[1][1].imshow(np.reshape(res[0], (LONGITUDE, WIDTH)))
            # plt.show()

        sess.run(train_op,feed_dict=feed_dict)
项目:a-nice-mc    作者:ermongroup    | 项目源码 | 文件源码
def __init__(self, name='expression', display=True):
        super(Expression, self).__init__()
        self.name = name
        self.display = display
        if display:
            import matplotlib.pyplot as plt
            plt.ion()
        else:
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
        self.fig, (self.ax1, self.ax2) = plt.subplots(nrows=2, ncols=1)
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def _finalize_plotting(self):
        from matplotlib import pyplot
        pyplot.tight_layout(rect=(0, 0, 0.96, 1))
        pyplot.draw()  # update "screen"
        pyplot.ion()  # prevents that the execution stops after plotting
        pyplot.show()
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def plot(self, plot_cmd=None, tf=lambda y: y):
        """plot the data we have, return ``self``"""
        from matplotlib import pyplot
        if not plot_cmd:
            plot_cmd = self.plot_cmd
        colors = 'bgrcmyk'
        pyplot.gcf().clear()
        res = self.res

        flatx, flatf = self.flattened()
        minf = np.inf
        for i in flatf:
            minf = min((minf, min(flatf[i])))
        addf = 1e-9 - minf if minf <= 1e-9 else 0
        for i in sorted(res.keys()):  # we plot not all values here
            if isinstance(i, int):
                color = colors[i % len(colors)]
                arx = sorted(res[i].keys())
                plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
                pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
                plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
        pyplot.ylabel('f + ' + str(addf))
        pyplot.draw()
        pyplot.ion()
        pyplot.show()
        return self
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def superpose(cdfs, outputpath, data):
    border_x = 0.5
    dx = 0.001
    x = np.arange(0, border_x, dx)
    plt.ioff()
    fig = plt.figure(figsize=(10,8))
    plt.xticks([0.01, 0.02, 0.05, 0.07, 0.09, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5])
    plt.yticks([0.1, 0.2, 0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
    plt.xticks(rotation=70)
    plt.grid(b=True, which='major', axis='both', linestyle='dotted')
    floating = 3
    prec = "%." + str(floating) + "f"
    for cdf in cdfs:
        title = cdf["title"]
        auc = cdf["auc"]
        cdf01 = cdf["cdf01"]
        cdf_val = cdf["cdf"]
        plt.plot(x, cdf_val, marker=',',
                 label=title + ", CDF(0.1)=" + str(prec % (cdf01*100)) + "%, AUC=" +
                 str(prec % np.float(auc)) + "%")
    plt.legend(loc=4, prop={'size': 8}, fancybox=True, shadow=True)
    fig.suptitle('Cumulative distribution function (CDF) of NRMSE over ' + data + ' test set.')
    plt.xlabel('NRMSE')
    plt.ylabel('Data proportion')
    fig.savefig(outputpath, bbox_inches='tight', format='eps', dpi=1000)
    plt.ion()
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def show_landmarks_unit_test(self, im, phis_pred, phis_mean_train, bbox, save=False, path="../im.png"):
        """ Display a shape over the face image. (python)


        phis_pred: predicted phis [xxxyyy]
        phis_mean_train: mean phis of ground of truth
        bbox=[x y w h]
        im = np.ndarray
        """
        plt.close('all')
        if save:
            plt.ioff()

        nfids = int(len(phis_pred)/2)
        plt.imshow(im, cmap = cm.Greys_r)
        gt = plt.scatter(x=phis_mean_train[0:nfids], y=phis_mean_train[nfids:], c='g', s=40)
        pr = plt.scatter(x=phis_pred[0:nfids], y=phis_pred[nfids:], c='r', s=20)

        mse = np.mean(np.power((phis_pred - phis_mean_train), 2))
        plt.legend((gt, pr), ("mean shape train", "prediction, MSE="+str(mse)), scatterpoints=1,loc='lower left', fontsize=8, fancybox=True, shadow=True)
        """
        plt.plot([bbox[0], bbox[0]],[bbox[1],bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0], bbox[0]+bbox[2]],[bbox[1], bbox[1]],'-b', linewidth=1)
        plt.plot([bbox[0]+bbox[2], bbox[0]+bbox[2]],[bbox[1], bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0] ,bbox[0]+bbox[2]],[bbox[1]+bbox[3] ,bbox[1]+bbox[3]],'-b', linewidth=1)
        """
        plt.axis('off')

        if save:
            plt.savefig(path,bbox_inches='tight', dpi=1000)
            plt.ion()
        else:
            plt.show()
            raw_input("... Press ENTER to continue,")

        plt.close('all')
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def __init__(self, size=(600,350)):
    streams = resolve_byprop('name', 'bci', timeout=2.5)
    try:
      self.inlet = StreamInlet(streams[0])
    except IndexError:
      raise ValueError('Make sure stream name=bci is opened first.')

    self.running = True

    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1
    self.sampleCount = self.count 
    self.maximum = 0
    self.minimum = 0

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Live Stream EEG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('mV')
    #plt.autoscale(True, 'y', tight = True)
    plt.show()
    #while(1):
    #secondTimes.append(serialData[0])                         #add time stamps to array 'timeValSeconds'
    #floatSecondTimes.append(float(serialData[0])/1000000)     # makes all second times into float from string

    #processedSig.append(serialData[6])                           #add processed signal values to 'processedSig'
    #floatProcessedSig.append(float(serialData[6]))
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def __init__(self, size=(600,350)):
    self.running = True
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Streaming Live EMG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('Volts')
    plt.show()
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
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

    # 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