• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python memory.Memory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中memory.Memory的典型用法代码示例。如果您正苦于以下问题:Python Memory类的具体用法?Python Memory怎么用?Python Memory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Memory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _determine_blockshape

    def _determine_blockshape(self, outputSlot):
        """
        Choose a blockshape using the slot metadata (if available) or an arbitrary guess otherwise.
        """
        input_shape = outputSlot.meta.shape
        ideal_blockshape = outputSlot.meta.ideal_blockshape
        ram_usage_per_requested_pixel = outputSlot.meta.ram_usage_per_requested_pixel

        num_channels = 1
        tagged_shape = outputSlot.meta.getTaggedShape()
        
        # Generally, we don't want to split requests across channels.
        if 'c' in tagged_shape.keys():
            num_channels = tagged_shape['c']
            channel_index = tagged_shape.keys().index('c')
            input_shape = input_shape[:channel_index] + input_shape[channel_index+1:]
            if ideal_blockshape:
                # Never enlarge 'ideal' in the channel dimension.
                num_channels = ideal_blockshape[channel_index]
                ideal_blockshape = ideal_blockshape[:channel_index] + ideal_blockshape[channel_index+1:]

        max_blockshape = input_shape
        available_ram = Memory.getAvailableRamComputation()
        
        if ram_usage_per_requested_pixel is None:
            # Make a conservative guess: 2*(bytes for dtype) * (num channels) + (fudge factor=4)
            ram_usage_per_requested_pixel = 2*outputSlot.meta.dtype().nbytes*num_channels + 4
            warnings.warn( "Unknown per-pixel RAM requirement.  Making a guess." )

        # Safety factor (fudge factor): Double the estimated RAM usage per pixel
        safety_factor = 2.0
        logger.info("Estimated RAM usage per pixel is {} * safety factor ({})"
                    .format( Memory.format(ram_usage_per_requested_pixel), safety_factor ) )
        ram_usage_per_requested_pixel *= safety_factor
        
        if ideal_blockshape is None:
            blockshape = determineBlockShape( input_shape, available_ram/(self._num_threads*ram_usage_per_requested_pixel) )
            if 'c' in outputSlot.meta.getAxisKeys():
                blockshape = blockshape[:channel_index] + (num_channels,) + blockshape[channel_index:]
            warnings.warn( "Chose an arbitrary request blockshape {}".format( blockshape ) )
        else:
            logger.info("determining blockshape assuming available_ram is {}"
                        ", split between {} threads"
                        .format(Memory.format(available_ram), self._num_threads))
            
            # By convention, ram_usage_per_requested_pixel refers to the ram used when requesting ALL channels of a 'pixel'
            # Therefore, we do not include the channel dimension in the blockshapes here.
            blockshape = determine_optimal_request_blockshape( max_blockshape,
                                                               ideal_blockshape,
                                                               ram_usage_per_requested_pixel, 
                                                               self._num_threads, 
                                                               available_ram )
            if 'c' in outputSlot.meta.getAxisKeys():
                blockshape = blockshape[:channel_index] + (num_channels,) + blockshape[channel_index:]
            logger.info( "Chose blockshape: {}".format( blockshape ) )
            fmt = Memory.format(ram_usage_per_requested_pixel *
                                numpy.prod(blockshape[:-1]))
            logger.info("Estimated RAM usage per block is {}".format(fmt))

        return blockshape
开发者ID:satishgoda,项目名称:lazyflow,代码行数:60,代码来源:bigRequestStreamer.py


示例2: Context

class Context(object):

    def __init__(self, instructions):
        self.registers = Registers()
        self.flags = Flags()
        self.instructions = instructions
        self.heap = Memory(size=40, mode=HEAP, start_address=0x0000)
        self.stack = Memory(size=40, mode=STACK, start_address=0xFFFF)
        self.registers.set(SP, 0xFFFF)

    def run(self):
        """
        initialize the context and execute the first instruction
        """
        self.registers.reset()

    def step(self):
        """
        execute the next instruction whose address in the EIP value
        :return:
        """
        self.registers.tick()
        self.flags.tick()
        self.heap.tick()
        self.stack.tick()
        next_address = self.registers.get(IP).value
        if next_address < len(self.instructions):
            next_instruction = self.instructions[next_address]
            next_instruction.execute(self)
            self.registers.set(IP, next_address + 1)
            return True
        else:
            return False
开发者ID:Groutcho,项目名称:exii,代码行数:33,代码来源:context.py


示例3: __init__

 def __init__(self, instructions):
     self.registers = Registers()
     self.flags = Flags()
     self.instructions = instructions
     self.heap = Memory(size=40, mode=HEAP, start_address=0x0000)
     self.stack = Memory(size=40, mode=STACK, start_address=0xFFFF)
     self.registers.set(SP, 0xFFFF)
开发者ID:Groutcho,项目名称:exii,代码行数:7,代码来源:context.py


示例4: __init__

 def __init__(self, parent, name, address, device_info=None, auto_update=False):
     self.auto_update = auto_update
     self.parent = parent
     self.last_values = {}
     Memory.__init__(self, name=name, width_bits=32, address=address, length_bytes=4)
     self.process_info(device_info)
     LOGGER.debug('New Register %s' % self)
开发者ID:james-smith-za,项目名称:casperfpga,代码行数:7,代码来源:register.py


示例5: try_alf_word

 def try_alf_word(self):
     if self.get() == '"':
         # exactly five mix-chars in inverted or
         self.next()
         if self.get() == '"':
             s = ""
         else:
             s = self.get()
             if self.look() != '"':
                 raise UnquotedStringError(self.line.argument)
             self.next()
     else:
         # less than six mix-chars not in inverted
         s = self.line.argument.rstrip('\n\r')
         self.ct = len(self.tokens) - 1
         if s is None:
             s = ""
     s = s[:5]
     while len(s) < 5:
         s += " "
     # now s - string with len = 5
     word = Memory.positive_zero()
     for i in xrange(1, 6):
         word[i] = charset.ord(s[i - 1])
         if word[i] is None:
             raise InvalidCharError(s[i - 1])
     return Memory.mix2dec(word)
开发者ID:JulienPalard,项目名称:mix-machine,代码行数:27,代码来源:parse_argument.py


示例6: try_w_exp

 def try_w_exp(self):
     """This function DO SELF.NEXT()"""
     word = Memory.positive_zero()
     value = self.try_exp()
     if value is None:
         return None
     if self.look() == "(":
         self.next()
         field = self.try_f_part()
     else:
         # it's property of w-exp that empty f-part means not default value
         # but 0:5
         field = 5
         self.next()
     if Memory.apply_to_word(value, word, field) is None:
         raise InvalidFieldSpecError(field)
     while True:
         if self.get() != ",":
             break
         self.next()
         value = self.try_exp()
         if value is None:
             raise ExpectedExpError(self.get_all_before_this())
         if self.look() == "(":
             self.next()
             field = self.try_f_part()
         else:
             field = get_codes(self.line.operation)[1]
             self.next()
         if Memory.apply_to_word(value, word, field) is None:
             raise InvalidFieldSpecError(field)
     return Memory.mix2dec(word)
开发者ID:JulienPalard,项目名称:mix-machine,代码行数:32,代码来源:parse_argument.py


示例7: __init__

	def __init__(self, env, model, epsilon=.9, min_epsilon=.1, epsilon_decay=1e-3):
		self.env = env
		self.model = model
		self.epsilon = epsilon
		self.min_epsilon = min_epsilon
		self.epsilon_decay = epsilon_decay
		self.episode = 0
		self.positiveMemory = Memory(model=self.model, episode_max_size=20)
		self.negativeMemory = Memory(model=self.model, episode_max_size=10)
开发者ID:blazer82,项目名称:ai,代码行数:9,代码来源:agent.py


示例8: memory

def memory():
    """
    Create Memory instance for testing.
    :return: new memory instance
    """
    from gb import GB
    from memory import Memory
    gb = GB()
    mem = Memory(gb)
    mem.load_cartridge(cartridge_data=bytes.fromhex("00")*0x8000)
    return mem
开发者ID:geosohh,项目名称:pgbe,代码行数:11,代码来源:test_memory.py


示例9: _build_memory

def _build_memory(screen):
    """ Initialize CPC464 memory map """
    memory = Memory(screen)
    memory.add_chunk(0x0000, RomChunk(_get_data_from_file('6128L.rom')))
    memory.add_chunk(0xC000, UpperRomChunk(0, _get_data_from_file('6128U-basic.rom')))
    memory.apply_ram_map(0)
    memory.dump_map()
    return memory
开发者ID:mxsscott,项目名称:cpyc,代码行数:8,代码来源:cpc6128.py


示例10: __init__

    def __init__(self, parent, name, address, length_bytes, device_info=None):
        """

        :param parent: Parent object who owns this TenGbe instance
        :param name: Unique name of the instance
        :param address:
        :param length_bytes:
        :param device_info: Information about this device
        :return:
        """
        Memory.__init__(self, name, 32, address, length_bytes)
        Gbe.__init__(self, parent, name, address, length_bytes, device_info)
开发者ID:ska-sa,项目名称:casperfpga,代码行数:12,代码来源:tengbe.py


示例11: run

def run(path, debug, max_cycles):
    with open(path, "rb") as rom_file:
        debug_title = debug == "TITLE"
        debug_header = debug == "HEADER" or debug == "ALL"
        debug_mem = debug == "MEMORY" or debug == "ALL"
        debug_instructions = debug == "INSTRUCTIONS" or debug == "ALL"
        debug_registers = debug == "REGISTERS" or debug == "ALL"
        rom = [i for i in rom_file.read()]
        
        header = Header(rom, debug_header)
        mem = Memory(rom, header)
        if debug_title:
            print("Title: " + header.name)
        if debug_instructions:
            print("PC:    Operation")
        
        interrupts = Interrupts()
        cpu = CPU(mem, interrupts, debug_instructions, debug_registers)
        timer = Timer(interrupts)
        sound = Sound()
        link = Link()
        joypad = Joypad()
        lcdc = LCDC(mem, interrupts)
        mem.setupIO(lcdc, interrupts, timer, sound, link, joypad)
        total_cycles = 0

        try:
            pygame.init()
            while cpu.run_state != "QUIT":
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        cpu.run_state = "QUIT"
                    if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                        joypad.keyEvent(event)

                interrupts.update()
                if cpu.run_state == "RUN":
                    cpu.run()
                else:
                    cpu.cycles += 1

                timer.update(cpu.cycles)
                lcdc.update(cpu.cycles)

                total_cycles += cpu.popCycles()
                if max_cycles >= 0 and total_cycles > max_cycles:
                    cpu.run_state = "QUIT"
        except AssertionError as e:
            if debug_mem:
                mem.display()
            traceback.print_tb(e.__traceback__)
        except KeyboardInterrupt as e:
            if debug_mem:
                mem.display()
        else:
            if debug_mem:
                mem.display()
开发者ID:rukai,项目名称:GameToy,代码行数:57,代码来源:gametoy.py


示例12: test

def test(test_iter, folds, training_folds):
    results = []
    mem = Memory()
    for i in range(test_iter):
        print "iteration %d ..." % (i + 1)
        ini_set = split_set2(folds, senseval.instances()[0:])
        for j in range(folds):
            print"...fold %d ..." % (j + 1)
            sets = partition_set(training_folds, ini_set, j)
            print "-$$Train time$$-"
            mem.train(sets[0])
            print "-$$results time$$-"
            results.append(mem.test(sets[1]))
    return results
开发者ID:jdesch,项目名称:MM-Algorithm,代码行数:14,代码来源:main.py


示例13: test_main

def test_main():
    mem = Memory()
    print "loading data_set"
    ini_set = split_set2(5, senseval.instances()[0:10000])
    data_set = partition_set(4, ini_set, 0)
    #Serializer.save("/tmp/portioned_data", data_set)
    #data_set = Serializer.load("/tmp/portioned_data")
    print "training data"
    mem.train(data_set[0])
    #print "saving data"
    #mem.save_values("/tmp/mem_internals")
    #mem.load_values("/tmp/mem_internals")
    print "------*********testing**********------"
    results = mem.test(data_set[1])
    print "%3.1f %% accuracy" %(sum(results)/len(results) * 100)
开发者ID:jdesch,项目名称:MM-Algorithm,代码行数:15,代码来源:main.py


示例14: __init__

    def __init__(self, queuetype, memtype, t_cs_val = 13):
        self.t_cs = t_cs_val 
        self.t_slice = 80 # in ms
        self.t_memmove = 10 # in ms
        if queuetype == "FCFS":
            self.process_queue = FCFSQueue() 
        elif queuetype == "SRT":
            self.process_queue = SRTQueue() 
        elif queuetype == "PWA":
            self.process_queue = PWAQueue() 
        elif queuetype == "RR":
            self.process_queue = FCFSQueue() 
 
        self.mem = Memory(memtype) 
        self.queueType = queuetype
        self.CPUIdle = True
        self.n = 0
        self.active_n = 0
        self.maxID = 1 
        self.processInCPU = None #Note: processInCPU is the process in use of CPU, NOT in content switch
        self.burstTimeSum = 0
        self.waitTimeSum = 0
        self.waitTimeNum = 0
        self.turnaroundTimeSum = 0
        self.contentSwitchSum = 0
        self.processInCPU_tobe = None 
        self.defragtime = 0
        self.p_list = []
开发者ID:xil12008,项目名称:operatingsystemproject,代码行数:28,代码来源:CPU.py


示例15: __init__

 def __init__(self, size_state, nr_actions, memorySize, discountFactor, learningRate, learnStart):
     self.input_size = size_state
     self.output_size = nr_actions
     self.memory = Memory(memorySize)
     self.discountFactor = discountFactor
     self.learnStart = learnStart
     self.learningRate = learningRate
开发者ID:vyraun,项目名称:deep-q-learning,代码行数:7,代码来源:deepq.py


示例16: __init__

    def __init__(self, config):
        self.config = config                                                    # 应用程序配置
        self.connections = 0                                                    # 连接客户端列表

        if self.config['savetime'] != 0:    # 不保存数据
            self.thread = PeriodicCallback(self.save_db,
                                       int(self.config['savetime']) * 1000)
            self.thread.start()                                                 # 背景保存服务线程启动

        self.workpool = ThreadPool(int(config['work_pool']))                    # 工作线程池

        self.status = Status(CacheServer.status_fields)                         # 服务器状态
        self.slave_clients = {}                                                 # 同步客户端
        self.is_sync = False                                                    # 是否在同步

        if self.config['master'] is not None:                                   # 从服务器启动
            shutil.rmtree(config['db'])
            self.master_server = PyCachedClient(self.config['master'][0],
                                                self.config['master'][1])
            self.master_server.sync(self.config['port'])
            self.slavepool = None
            self.slave = True                                                   # 是否为Slave模式
        else:                                                                   # 主服务器启动, 需要启动从命令工作线程

            self.slavepool = ThreadPool(int(config['slave_pool']))              # slave Command send pools
            self.slave = False                                                  # 是否为Slave模式

        self.memory = Memory(config['db'])                                      # 缓存服务类
        super(CacheServer, self).__init__()
开发者ID:eicesoft,项目名称:pycached,代码行数:29,代码来源:net.py


示例17: __init__

    def __init__(self, obs_dim, action_dim, hiddens_actor, hiddens_critic, layer_norm=False, memory_size=50000):
        self.obs_dim = obs_dim
        self.action_dim = action_dim

        self.noise_stddev = 1.
        self.noise_stddev_decrease = 5e-4
        self.noise_stddev_lower = 5e-2

        actor_activations = [dy.tanh for _ in range(len(hiddens_actor))] + [dy.tanh]
        critic_activations = [dy.tanh for _ in range(len(hiddens_critic))] + [None]
        self.actor = MLP(inpt_shape=(obs_dim,), hiddens=hiddens_actor + [action_dim], activation=actor_activations,
                         layer_norm=layer_norm)
        self.critic = MLP(inpt_shape=(obs_dim + action_dim,), hiddens=hiddens_critic + [1],
                          activation=critic_activations, layer_norm=layer_norm)
        self.actor_target = MLP(inpt_shape=(obs_dim,), hiddens=hiddens_actor + [action_dim],
                                activation=actor_activations, layer_norm=layer_norm)
        self.critic_target = MLP(inpt_shape=(obs_dim + action_dim,), hiddens=hiddens_critic + [1],
                                 activation=critic_activations, layer_norm=layer_norm)
        self.actor_target.update(self.actor, soft=False)
        self.critic_target.update(self.critic, soft=False)

        self.trainer_actor = dy.AdamTrainer(self.actor.pc)
        self.trainer_critic = dy.AdamTrainer(self.critic.pc)
        self.trainer_actor.set_learning_rate(1e-4)
        self.trainer_critic.set_learning_rate(1e-3)

        self.memory = Memory(memory_size)
开发者ID:danielhers,项目名称:cnn,代码行数:27,代码来源:ddpg.py


示例18: __init__

 def __init__(self):
     self.memory = Memory()
     self.OPERATORS = {":=" : self.opDefine, "<<" : self.opDefineKeyword, "++" : self.opIncrement}
     self.COMMANDS  = {"remember" : self.comRemember, "recall" : self.comFindQuote, 
                 "evaluate" : self.comEvaluate, "count" : self.comCount, "findfactoid" : self.comFactoidSearch,
                 "findquote" : self.comQuoteSearch, "delete" : self.comDeleteFactoid }
     self.PROCESSCOMMANDS  = {"remember" :  False, "recall" : False, "evaluate" : True, "count" : False,
                 "findfactoid" : False, "findquote" : False, "delete" : False }
开发者ID:JordanMatuschka,项目名称:grossmaul,代码行数:8,代码来源:botbrain.py


示例19: __init__

    def __init__(self, env, params):
        self.env = env
        params.actions = env.actions()
        self.num_actions = env.actions()
        self.episodes = params.episodes
        self.steps = params.steps
        self.train_steps = params.train_steps
        self.update_freq = params.update_freq
        self.save_weights = params.save_weights
        self.history_length = params.history_length
        self.discount = params.discount
        self.eps = params.init_eps
        self.eps_delta = (params.init_eps - params.final_eps) / params.final_eps_frame
        self.replay_start_size = params.replay_start_size
        self.eps_endt = params.final_eps_frame
        self.random_starts = params.random_starts
        self.batch_size = params.batch_size
        self.ckpt_file = params.ckpt_dir+'/'+params.game

        self.global_step = tf.Variable(0, trainable=False)
        if params.lr_anneal:
            self.lr = tf.train.exponential_decay(params.lr, self.global_step, params.lr_anneal, 0.96, staircase=True)
        else:
            self.lr = params.lr

        self.buffer = Buffer(params)
        self.memory = Memory(params.size, self.batch_size)

        with tf.variable_scope("train") as self.train_scope:
            self.train_net = ConvNet(params, trainable=True)
        with tf.variable_scope("target") as self.target_scope:
            self.target_net = ConvNet(params, trainable=False)

        self.optimizer = tf.train.RMSPropOptimizer(self.lr, params.decay_rate, 0.0, self.eps)

        self.actions = tf.placeholder(tf.float32, [None, self.num_actions])
        self.q_target = tf.placeholder(tf.float32, [None])
        self.q_train = tf.reduce_max(tf.mul(self.train_net.y, self.actions), reduction_indices=1)
        self.diff = tf.sub(self.q_target, self.q_train)

        half = tf.constant(0.5)
        if params.clip_delta > 0:
            abs_diff = tf.abs(self.diff)
            clipped_diff = tf.clip_by_value(abs_diff, 0, 1)
            linear_part = abs_diff - clipped_diff
            quadratic_part = tf.square(clipped_diff)
            self.diff_square = tf.mul(half, tf.add(quadratic_part, linear_part))
        else:
            self.diff_square = tf.mul(half, tf.square(self.diff))

        if params.accumulator == 'sum':
            self.loss = tf.reduce_sum(self.diff_square)
        else:
            self.loss = tf.reduce_mean(self.diff_square)

        # backprop with RMS loss
        self.task = self.optimizer.minimize(self.loss, global_step=self.global_step)
开发者ID:chagge,项目名称:Game-AI,代码行数:57,代码来源:dqn.py


示例20: __init__

 def __init__(self):
     '''
     Births a new Parrott,
     with a Naive Bayes brain
     and a Solr memory.
     '''
     self.brain = naive_bayes.NaiveBayes()
     self.twitter = membrane.twitter.api()
     self.memory = Memory()
开发者ID:frnsys,项目名称:parrott,代码行数:9,代码来源:parrott.py



注:本文中的memory.Memory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python memory_profiler.memory_usage函数代码示例发布时间:2022-05-27
下一篇:
Python memory.make_object函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap