Python numpy.flatten() Examples
The following are 2 code examples for showing how to use numpy.flatten(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: adversarial-policies Author: HumanCompatibleAI File: multi_agent.py License: MIT License | 5 votes |
def flatten_space(tuple_space): """Flattens a Tuple of like-spaces into a single bigger space of the appropriate type. The spaces do not have to have the same shape, but do need to be of compatible types. For example, we can flatten a (Box(10), Box(5)) into Box(15) or a (Discrete(2), Discrete(2)) into a MultiDiscrete([2, 2]), but cannot flatten a (Box(10), Discrete(2)).""" unique_types = set(type(space) for space in tuple_space.spaces) if len(unique_types) > 1: raise TypeError(f"Cannot flatten a space with more than one type: {unique_types}") uniq_type = unique_types.pop() if isinstance(uniq_type, gym.spaces.Discrete): flat_space = gym.spaces.MultiDiscrete([space.n for space in tuple_space.spaces]) flatten = unflatten = lambda x: x elif isinstance(uniq_type, gym.spaces.MultiDiscrete): flat_space = gym.spaces.MultiDiscrete([space.nvec for space in tuple_space.spaces]) flatten = unflatten = lambda x: x elif isinstance(uniq_type, gym.spaces.Box): low = np.concatenate(*[space.low for space in tuple_space.spaces], axis=0) high = np.concatenate(*[space.high for space in tuple_space.spaces], axis=0) flat_space = gym.spaces.Box(low=low, high=high) def flatten(x): return np.flatten(x) def unflatten(x): sizes = [np.prod(space.shape) for space in tuple_space.spaces] start = np.cumsum(sizes) end = start[1:] + len(x) orig = [ np.reshape(x[s:e], space.shape) for s, e, space in zip(start, end, tuple_space.spaces) ] return orig else: raise NotImplementedError("Unsupported type: f{type}") return flat_space, flatten, unflatten
Example 2
Project: PaddlePaddle_code Author: huxiaoman7 File: conv.py License: Apache License 2.0 | 5 votes |
def eval(self,x): # 补零后的宽度ww和高度hh ww = self.h - self.k_x + 2 * self.p_x + 1 hh = self.h - self.k_y + 2 * self.p_y + 1 ret = np.array([[[np.ravel(xx[:, a:a + self.k_x, b:b + self.k_y]) for b in range(0, hh, self.s_y)] for a in range(0, ww, self.s_x)] for xx in x]) #ret = np.array([[[np.ravel(xx[:,a:a +self.k_x, b:b, self.k_y]) for b in range(0,hh,self.s_y)] for a in range(0,ww,self.s_x)] for xx in x])# here using np.ravel rather than np.flatten to save memory return ret