Search is not available for this dataset
text
stringlengths
75
104k
def from_spec(spec, kwargs): """ Creates an agent from a specification dict. """ agent = util.get_object( obj=spec, predefined_objects=tensorforce.agents.agents, kwargs=kwargs ) assert isinstance(agent, Agent) return agent
def get_named_tensor(self, name): """ Returns a named tensor if available. Returns: valid: True if named tensor found, False otherwise tensor: If valid, will be a tensor, otherwise None """ if name in self.named_tensors: return True, self.name...
def from_spec(spec, kwargs=None): """ Creates a network from a specification dict. """ network = util.get_object( obj=spec, default_object=LayeredNetwork, kwargs=kwargs ) assert isinstance(network, Network) return network
def put(self, item, priority=None): """ Stores a transition in replay memory. If the memory is full, the oldest entry is replaced. """ if not self._isfull(): self._memory.append(None) position = self._next_position_then_increment() old_priority = 0 if...
def move(self, external_index, new_priority): """ Change the priority of a leaf node """ index = external_index + (self._capacity - 1) return self._move(index, new_priority)
def _move(self, index, new_priority): """ Change the priority of a leaf node. """ item, old_priority = self._memory[index] old_priority = old_priority or 0 self._memory[index] = _SumRow(item, new_priority) self._update_internal_nodes(index, new_priority - old_prio...
def _update_internal_nodes(self, index, delta): """ Update internal priority sums when leaf priority has been changed. Args: index: leaf node index delta: change in priority """ # Move up tree, increasing position, updating sum while index > 0: ...
def _next_position_then_increment(self): """ Similar to position++. """ start = self._capacity - 1 position = start + self._position self._position = (self._position + 1) % self._capacity return position
def _sample_with_priority(self, p): """ Sample random element with priority greater than p. """ parent = 0 while True: left = 2 * parent + 1 if left >= len(self._memory): # parent points to a leaf node already. return parent...
def sample_minibatch(self, batch_size): """ Sample minibatch of size batch_size. """ pool_size = len(self) if pool_size == 0: return [] delta_p = self._memory[0] / batch_size chosen_idx = [] # if all priorities sum to ~0 choose randomly other...
def get_batch(self, batch_size, next_states=False): """ Samples a batch of the specified size according to priority. Args: batch_size: The batch size next_states: A boolean flag indicating whether 'next_states' values should be included Returns: A dict containin...
def update_batch(self, loss_per_instance): """ Computes priorities according to loss. Args: loss_per_instance: """ if self.batch_indices is None: raise TensorForceError("Need to call get_batch before each update_batch call.") # if len(loss_per_in...
def import_experience(self, experiences): """ Imports experiences. Args: experiences: """ if isinstance(experiences, dict): if self.unique_state: experiences['states'] = dict(state=experiences['states']) if self.unique_action:...
def connect(self, timeout=600): """ Starts the server tcp connection on the given host:port. Args: timeout (int): The time (in seconds) for which we will attempt a connection to the remote (every 5sec). After that (or if timeout is None or 0), an error is raised. ...
def disconnect(self): """ Ends our server tcp connection. """ # If we are not connected, return error. if not self.socket: logging.warning("No active socket to close!") return # Close our socket. self.socket.close() self.socket = No...
def send(self, message, socket_): """ Sends a message (dict) to the socket. Message consists of a 8-byte len header followed by a msgpack-numpy encoded dict. Args: message: The message dict (e.g. {"cmd": "reset"}) socket_: The python socket object to use. ...
def recv(self, socket_, encoding=None): """ Receives a message as msgpack-numpy encoded byte-string from the given socket object. Blocks until something was received. Args: socket_: The python socket object to use. encoding (str): The encoding to use for unpackin...
def is_action_available(self, action): """Determines whether action is available. That is, executing it would change the state. """ temp_state = np.rot90(self._state, action) return self._is_action_available_left(temp_state)
def _is_action_available_left(self, state): """Determines whether action 'Left' is available.""" # True if any field is 0 (empty) on the left of a tile or two tiles can # be merged. for row in range(4): has_empty = False for col in range(4): has_e...
def do_action(self, action): """Execute action, add a new tile, update the score & return the reward.""" temp_state = np.rot90(self._state, action) reward = self._do_action_left(temp_state) self._state = np.rot90(temp_state, -action) self._score += reward self.add_rando...
def _do_action_left(self, state): """Executes action 'Left'.""" reward = 0 for row in range(4): # Always the rightmost tile in the current row that was already moved merge_candidate = -1 merged = np.zeros((4,), dtype=np.bool) for col in range(4)...
def add_random_tile(self): """Adds a random tile to the grid. Assumes that it has empty fields.""" x_pos, y_pos = np.where(self._state == 0) assert len(x_pos) != 0 empty_index = np.random.choice(len(x_pos)) value = np.random.choice([1, 2], p=[0.9, 0.1]) self._state[x_po...
def print_state(self): """Prints the current state.""" def tile_string(value): """Concert value to string.""" if value > 0: return '% 5d' % (2 ** value,) return " " separator_line = '-' * 25 print(separator_line) for row i...
def setup(self): """ Sets up the TensorFlow model graph, starts the servers (distributed mode), creates summarizers and savers, initializes (and enters) the TensorFlow session. """ # Create/get our graph, setup local model/global model links, set scope and device. graph_...
def setup_graph(self): """ Creates our Graph and figures out, which shared/global model to hook up to. If we are in a global-model's setup procedure, we do not create a new graph (return None as the context). We will instead use the already existing local replica graph of the mod...
def start_server(self): """ Creates and stores a tf server (and optionally joins it if we are a parameter-server). Only relevant, if we are running in distributed mode. """ self.server = tf.train.Server( server_or_cluster_def=self.distributed_spec["cluster_spec"], ...
def setup_placeholders(self): """ Creates the TensorFlow placeholders, variables, ops and functions for this model. NOTE: Does not add the internal state placeholders and initialization values to the model yet as that requires the model's Network (if any) to be generated first. "...
def setup_components_and_tf_funcs(self, custom_getter=None): """ Allows child models to create model's component objects, such as optimizer(s), memory(s), etc.. Creates all tensorflow functions via tf.make_template calls on all the class' "tf_"-methods. Args: custom_getter: ...
def setup_saver(self): """ Creates the tf.train.Saver object and stores it in self.saver. """ if self.execution_type == "single": global_variables = self.get_variables(include_submodules=True, include_nontrainable=True) else: global_variables = self.global...
def setup_scaffold(self): """ Creates the tf.train.Scaffold object and assigns it to self.scaffold. Other fields of the Scaffold are generated automatically. """ if self.execution_type == "single": global_variables = self.get_variables(include_submodules=True, include...
def setup_hooks(self): """ Creates and returns a list of hooks to use in a session. Populates self.saver_directory. Returns: List of hooks to use in a session. """ hooks = list() # Checkpoint saver hook if self.saver_spec is not None and (self.execution_type == ...
def setup_session(self, server, hooks, graph_default_context): """ Creates and then enters the session for this model (finalizes the graph). Args: server (tf.train.Server): The tf.train.Server object to connect to (None for single execution). hooks (list): A list of (sav...
def close(self): """ Saves the model (of saver dir is given) and closes the session. """ if self.flush_summarizer is not None: self.monitored_session.run(fetches=self.flush_summarizer) if self.saver_directory is not None: self.save(append_timestep=True) ...
def tf_initialize(self): """ Creates tf Variables for the local state/internals/action-buffers and for the local and global counters for timestep and episode. """ # Timesteps/Episodes # Global: (force on global device; local and global model point to the same (global) da...
def tf_preprocess(self, states, actions, reward): """ Applies preprocessing ops to the raw states/action/reward inputs. Args: states (dict): Dict of raw state tensors. actions (dict): Dict or raw action tensors. reward: 1D (float) raw rewards tensor. ...
def tf_action_exploration(self, action, exploration, action_spec): """ Applies optional exploration to the action (post-processor for action outputs). Args: action (tf.Tensor): The original output action tensor (to be post-processed). exploration (Exploration): The Exp...
def create_act_operations(self, states, internals, deterministic, independent, index): """ Creates and stores tf operations that are fetched when calling act(): actions_output, internals_output and timestep_output. Args: states (dict): Dict of state tensors (each key represe...
def create_observe_operations(self, terminal, reward, index): """ Returns the tf op to fetch when an observation batch is passed in (e.g. an episode's rewards and terminals). Uses the filled tf buffers for states, actions and internals to run the tf_observe_timestep (model-dependent), re...
def create_atomic_observe_operations(self, states, actions, internals, terminal, reward, index): """ Returns the tf op to fetch when unbuffered observations are passed in. Args: states (any): One state (usually a value tuple) or dict of states if multiple states are expected. ...
def create_operations(self, states, internals, actions, terminal, reward, deterministic, independent, index): """ Creates and stores tf operations for when `act()` and `observe()` are called. """ self.create_act_operations( states=states, internals=internals, ...
def get_variables(self, include_submodules=False, include_nontrainable=False): """ Returns the TensorFlow variables used by the model. Args: include_submodules: Includes variables of submodules (e.g. baseline, target network) if true. include_nontrainable...
def reset(self): """ Resets the model to its initial state on episode start. This should also reset all preprocessor(s). Returns: tuple: Current episode, timestep counter and the shallow-copied list of internal state initialization Tensors. """ fetche...
def get_feed_dict( self, states=None, internals=None, actions=None, terminal=None, reward=None, deterministic=None, independent=None, index=None ): """ Returns the feed-dict for the model's acting and observing tf fetches. ...
def act(self, states, internals, deterministic=False, independent=False, fetch_tensors=None, index=0): """ Does a forward pass through the model to retrieve action (outputs) given inputs for state (and internal state, if applicable (e.g. RNNs)) Args: states (dict): Dict of s...
def observe(self, terminal, reward, index=0): """ Adds an observation (reward and is-terminal) to the model without updating its trainable variables. Args: terminal (List[bool]): List of is-terminal signals. reward (List[float]): List of reward signals. index...
def save(self, directory=None, append_timestep=True): """ Save TensorFlow model. If no checkpoint directory is given, the model's default saver directory is used. Optionally appends current timestep to prevent overwriting previous checkpoint files. Turn off to be able to load model from ...
def restore(self, directory=None, file=None): """ Restore TensorFlow model. If no checkpoint file is given, the latest checkpoint is restored. If no checkpoint directory is given, the model's default saver directory is used (unless file specifies the entire path). Args: ...
def get_savable_components(self): """ Returns the list of all of the components this model consists of that can be individually saved and restored. For instance the network or distribution. Returns: List of util.SavableComponent """ components = self.get_comp...
def save_component(self, component_name, save_path): """ Saves a component of this model to the designated location. Args: component_name: The component to save. save_path: The location to save to. Returns: Checkpoint path where the component was save...
def restore_component(self, component_name, save_path): """ Restores a component's parameters from a save location. Args: component_name: The component to restore. save_path: The save location. """ component = self.get_component(component_name=component_n...
def get_component(self, component_name): """ Looks up a component by its name. Args: component_name: The name of the component to look up. Returns: The component for the provided name or None if there is no such component. """ mapping = self.get_c...
def import_demonstrations(self, demonstrations): """ Imports demonstrations, i.e. expert observations. Note that for large numbers of observations, set_demonstrations is more appropriate, which directly sets memory contents to an array an expects a different layout. Args: ...
def seed(self, seed): # pylint: disable=E0202 """ Sets the random seed of the environment to the given value (current time, if seed=None). Naturally deterministic Environments (e.g. ALE or some gym Envs) don't have to implement this method. Args: seed (int): The seed to use ...
def execute(self, action): """ Executes action, observes next state and reward. Args: actions: Action to execute. Returns: (Dict of) next state(s), boolean indicating terminal, and reward signal. """ if self.env.game_over(): return se...
def states(self): """ Return the state space. Might include subdicts if multiple states are available simultaneously. Returns: dict of state properties (shape and type). """ screen = self.env.getScreenRGB() return dict(shape=screen.shape, type='int')
def sanity_check_states(states_spec): """ Sanity checks a states dict, used to define the state space for an MDP. Throws an error or warns if mismatches are found. Args: states_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the state space desc and 2) wheth...
def sanity_check_actions(actions_spec): """ Sanity checks an actions dict, used to define the action space for an MDP. Throws an error or warns if mismatches are found. Args: actions_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the action space desc and 2...
def sanity_check_execution_spec(execution_spec): """ Sanity checks a execution_spec dict, used to define execution logic (distributed vs single, shared memories, etc..) and distributed learning behavior of agents/models. Throws an error or warns if mismatches are found. Args: execution_spec...
def make_game(): """Builds and returns an Extraterrestrial Marauders game.""" return ascii_art.ascii_art_to_game( GAME_ART, what_lies_beneath=' ', sprites=dict( [('P', PlayerSprite)] + [(c, UpwardLaserBoltSprite) for c in UPWARD_BOLT_CHARS] + [(c, DownwardLaserBoltSprite) f...
def _fly(self, board, layers, things, the_plot): """Handles the behaviour of visible bolts flying toward Marauders.""" # Disappear if we've hit a Marauder or a bunker. if (self.character in the_plot['bunker_hitters'] or self.character in the_plot['marauder_hitters']): return self._teleport((-1...
def _fire(self, layers, things, the_plot): """Launches a new bolt from the player.""" # We don't fire if the player fired another bolt just now. if the_plot.get('last_player_shot') == the_plot.frame: return the_plot['last_player_shot'] = the_plot.frame # We start just above the player. row, col ...
def _fly(self, board, layers, things, the_plot): """Handles the behaviour of visible bolts flying toward the player.""" # Disappear if we've hit a bunker. if self.character in the_plot['bunker_hitters']: return self._teleport((-1, -1)) # End the game if we've hit the player. if self.position =...
def _fire(self, layers, the_plot): """Launches a new bolt from a random Marauder.""" # We don't fire if another Marauder fired a bolt just now. if the_plot.get('last_marauder_shot') == the_plot.frame: return the_plot['last_marauder_shot'] = the_plot.frame # Which Marauder should fire the laser bolt?...
def reset(self, history=None): """ Resets the Runner's internal stats counters. If history is empty, use default values in history.get(). Args: history (dict): A dictionary containing an already run experiment's results. Keys should be: episode_rewards (list ...
def run(self, num_episodes, num_timesteps, max_episode_timesteps, deterministic, episode_finished, summary_report, summary_interval): """ Executes this runner by starting to act (via Agent(s)) in the given Environment(s). Stops execution according to certain conditions (e.g. max. num...
def tf_retrieve_indices(self, buffer_elements, priority_indices): """ Fetches experiences for given indices by combining entries from buffer which have no priorities, and entries from priority memory. Args: buffer_elements: Number of buffer elements to retrieve p...
def tf_update_batch(self, loss_per_instance): """ Updates priority memory by performing the following steps: 1. Use saved indices from prior retrieval to reconstruct the batch elements which will have their priorities updated. 2. Compute priorities for these elements. 3....
def setup_components_and_tf_funcs(self, custom_getter=None): """ Creates and stores Network and Distribution objects. Generates and stores all template functions. """ # Create network before super-call, since non-empty internals_spec attribute (for RNN) is required subsequently. ...
def create_distributions(self): """ Creates and returns the Distribution objects based on self.distributions_spec. Returns: Dict of distributions according to self.distributions_spec. """ distributions = dict() for name in sorted(self.actions_spec): action = ...
def from_spec(spec): """ Creates an exploration object from a specification dict. """ exploration = util.get_object( obj=spec, predefined_objects=tensorforce.core.explorations.explorations ) assert isinstance(exploration, Exploration) retur...
def from_spec(spec, kwargs=None): """ Creates a memory from a specification dict. """ memory = util.get_object( obj=spec, predefined_objects=tensorforce.core.memories.memories, kwargs=kwargs ) assert isinstance(memory, Memory) r...
def tf_step( self, time, variables, arguments, **kwargs ): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. arguments: Dic...
def run(self, num_timesteps=None, num_episodes=None, max_episode_timesteps=None, deterministic=False, episode_finished=None, summary_report=None, summary_interval=None, timesteps=None, episodes=None, testing=False, sleep=None ): """ Args: timesteps (int): Deprecated; ...
def tf_retrieve_indices(self, indices): """ Fetches experiences for given indices. Args: indices: Index tensor Returns: Batch of experiences """ states = dict() for name in sorted(self.states_memory): states[name] = tf.gather(params=self....
def tf_solve(self, fn_x, x_init, base_value, target_value, estimated_improvement=None): """ Iteratively optimizes $f(x)$ for $x$ on the line between $x'$ and $x_0$. Args: fn_x: A callable returning the value $f(x)$ at $x$. x_init: Initial solution guess $x_0$. ...
def tf_initialize(self, x_init, base_value, target_value, estimated_improvement): """ Initialization step preparing the arguments for the first iteration of the loop body. Args: x_init: Initial solution guess $x_0$. base_value: Value $f(x')$ at $x = x'$. targ...
def tf_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement): """ Iteration loop body of the line search algorithm. Args: x: Current solution estimate $x_t$. iteration: Current iteration counter $t$. deltas: Current difference...
def tf_next_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement): """ Termination condition: max number of iterations, or no improvement for last step, or improvement less than acceptable ratio, or estimated value not positive. Args: x: Cu...
def escape(text, quote=False, smart_amp=True): """Replace special characters "&", "<" and ">" to HTML-safe sequences. The original cgi.escape will always escape "&", but you can control this one for a smart escape amp. :param quote: if set to True, " and ' will be escaped. :param smart_amp: if set...
def escape_link(url): """Remove dangerous URL schemes like javascript: and escape afterwards.""" lower_url = url.lower().strip('\x00\x1a \n\r\t') for scheme in _scheme_blacklist: if lower_url.startswith(scheme): return '' return escape(url, quote=True, smart_amp=False)
def markdown(text, escape=True, **kwargs): """Render markdown formatted text to html. :param text: markdown formatted text content. :param escape: if set to False, all html tags will not be escaped. :param use_xhtml: output with xhtml tags. :param hard_wrap: if set to True, it will use the GFM line...
def parse_lheading(self, m): """Parse setext heading.""" self.tokens.append({ 'type': 'heading', 'level': 1 if m.group(2) == '=' else 2, 'text': m.group(1), })
def hard_wrap(self): """Grammar for hard wrap linebreak. You don't need to add two spaces at the end of a line. """ self.linebreak = re.compile(r'^ *\n(?!\s*$)') self.text = re.compile( r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)' )
def block_code(self, code, lang=None): """Rendering block level code. ``pre > code``. :param code: text content of the code block. :param lang: language of the given code. """ code = code.rstrip('\n') if not lang: code = escape(code, smart_amp=False) ...
def block_html(self, html): """Rendering block level pure html content. :param html: text content of the html snippet. """ if self.options.get('skip_style') and \ html.lower().startswith('<style'): return '' if self.options.get('escape'): retur...
def list(self, body, ordered=True): """Rendering list tags like ``<ul>`` and ``<ol>``. :param body: body contents of the list. :param ordered: whether this list is ordered or not. """ tag = 'ul' if ordered: tag = 'ol' return '<%s>\n%s</%s>\n' % (tag, ...
def table_cell(self, content, **flags): """Rendering a table cell. Like ``<th>`` ``<td>``. :param content: content of current table cell. :param header: whether this is header or not. :param align: align of current table cell. """ if flags['header']: tag = 't...
def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ text = escape(text.rstrip(), smart_amp=False) return '<code>%s</code>' % text
def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ text = link = escape(link) if is_email: link = 'mailto:%s' % link r...
def link(self, link, title, text): """Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description. """ link = escape_link(link) if not title: ...
def image(self, src, title, text): """Rendering a image with title and text. :param src: source link of the image. :param title: title text of the image. :param text: alt text of the image. """ src = escape_link(src) text = escape(text, quote=True) if tit...
def footnote_ref(self, key, index): """Rendering the ref anchor of a footnote. :param key: identity key for the footnote. :param index: the index count of current footnote. """ html = ( '<sup class="footnote-ref" id="fnref-%s">' '<a href="#fn-%s">%d</a></...
def footnote_item(self, key, text): """Rendering a footnote item. :param key: identity key for the footnote. :param text: text content of the footnote. """ back = ( '<a href="#fnref-%s" class="footnote">&#8617;</a>' ) % escape(key) text = text.rstrip(...
def build_metagraph_list(self): """ Convert MetaParams into TF Summary Format and create summary_op. Returns: Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication. """ ops = [] self.ignore_unknown_dtypes = True ...
def process_docstring(app, what, name, obj, options, lines): """Enable markdown syntax in docstrings""" markdown = "\n".join(lines) # ast = cm_parser.parse(markdown) # html = cm_renderer.render(ast) rest = m2r(markdown) rest.replace("\r\n", "\n") del lines[:] lines.extend(rest.spl...
def tf_step( self, time, variables, arguments, fn_loss, fn_kl_divergence, return_estimated_improvement=False, **kwargs ): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time t...
def tf_step(self, time, variables, arguments, fn_reference=None, **kwargs): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. arguments: Dict of arguments for callable...
def tf_baseline_loss(self, states, internals, reward, update, reference=None): """ Creates the TensorFlow operations for calculating the baseline loss of a batch. Args: states: Dict of state tensors. internals: List of prior internal state tensors. reward: Re...
def baseline_optimizer_arguments(self, states, internals, reward): """ Returns the baseline optimizer arguments including the time, the list of variables to optimize, and various functions which the optimizer might require to perform an update step. Args: states:...
def tf_step(self, time, variables, source_variables, **kwargs): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. source_variables: List of source variables to synchro...