Python numpy.around() Examples

The following are 30 code examples of numpy.around(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: coco.py    From dataiku-contrib with Apache License 2.0 7 votes vote down vote up
def build_coco_results(dataset, image_ids, rois, class_ids, scores, masks):
    """Arrange resutls to match COCO specs in http://cocodataset.org/#format
    """
    # If no results, return an empty list
    if rois is None:
        return []

    results = []
    for image_id in image_ids:
        # Loop through detections
        for i in range(rois.shape[0]):
            class_id = class_ids[i]
            score = scores[i]
            bbox = np.around(rois[i], 1)
            mask = masks[:, :, i]

            result = {
                "image_id": image_id,
                "category_id": dataset.get_source_class_id(class_id, "coco"),
                "bbox": [bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0]],
                "score": score,
                "segmentation": maskUtils.encode(np.asfortranarray(mask))
            }
            results.append(result)
    return results 
Example #2
Source File: test_arithmetic_execution.py    From mars with Apache License 2.0 6 votes vote down vote up
def testAroundExecution(self):
        data = np.random.randn(10, 20)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data, decimals=2)

        np.testing.assert_allclose(res, expected)

        data = sps.random(10, 20, density=.2)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data.toarray(), decimals=2)

        np.testing.assert_allclose(res.toarray(), expected) 
Example #3
Source File: testutils.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #4
Source File: molecule.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def float_prep(array, around):
    """
    Rounds floats to a common value and build positive zeros to prevent hash conflicts.
    """
    if isinstance(array, (list, np.ndarray)):
        # Round array
        array = np.around(array, around)
        # Flip zeros
        array[np.abs(array) < 5 ** (-(around + 1))] = 0

    elif isinstance(array, (float, int)):
        array = round(array, around)
        if array == -0.0:
            array = 0.0
    else:
        raise TypeError("Type '{}' not recognized".format(type(array).__name__))

    return array 
Example #5
Source File: fromnumeric.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 
Example #6
Source File: env_problem.py    From tensor2tensor with Apache License 2.0 6 votes vote down vote up
def process_rewards(self, rewards):
    """Clips the rewards, optionally rounds them and casts to integer.

    Args:
      rewards: numpy array of raw (float) rewards.

    Returns:
      processed_rewards: numpy array of np.int64
    """

    min_reward, max_reward = self.reward_range

    # Clips at min and max reward.
    rewards = np.clip(rewards, min_reward, max_reward)

    if self._discrete_rewards:
      # Round to (nearest) int and convert to integral type.
      rewards = np.around(rewards, decimals=0).astype(np.int64)
    return rewards 
Example #7
Source File: utils.py    From dataiku-contrib with Apache License 2.0 6 votes vote down vote up
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()
    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
Example #8
Source File: utils.py    From dataiku-contrib with Apache License 2.0 6 votes vote down vote up
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().
    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
Example #9
Source File: testutils.py    From lambda-packs with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #10
Source File: test_panel.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_numpy_round(self):
        values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
                   [-1566.213, 88.88], [-12, 94.5]],
                  [[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
                   [272.212, -99.99], [23, -76.5]]]
        evalues = [[[float(np.around(i)) for i in j] for j in k]
                   for k in values]
        p = Panel(values, items=['Item1', 'Item2'],
                  major_axis=date_range('1/1/2000', periods=5),
                  minor_axis=['A', 'B'])
        expected = Panel(evalues, items=['Item1', 'Item2'],
                         major_axis=date_range('1/1/2000', periods=5),
                         minor_axis=['A', 'B'])
        result = np.round(p)
        assert_panel_equal(expected, result)

        msg = "the 'out' parameter is not supported"
        with pytest.raises(ValueError, match=msg):
            np.round(p, out=p)

    # removing Panel before NumPy enforces, so just ignore 
Example #11
Source File: utils.py    From PanopticSegmentation with MIT License 6 votes vote down vote up
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().

    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
Example #12
Source File: utils.py    From PanopticSegmentation with MIT License 6 votes vote down vote up
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()

    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
Example #13
Source File: bitcoinotc.py    From dgl with Apache License 2.0 6 votes vote down vote up
def _load(self, filename):
        data = np.loadtxt(filename, delimiter=',').astype(np.int64)
        data[:, 0:2] = data[:, 0:2] - data[:, 0:2].min()
        num_nodes = data[:, 0:2].max() - data[:, 0:2].min() + 1
        delta = datetime.timedelta(days=14).total_seconds()
        # The source code is not released, but the paper indicates there're
        # totally 137 samples. The cutoff below has exactly 137 samples.
        time_index = np.around(
            (data[:, 3] - data[:, 3].min())/delta).astype(np.int64)
        for i in range(time_index.max()):
            g = DGLGraph()
            g.add_nodes(num_nodes)
            row_mask = time_index <= i
            edges = data[row_mask][:, 0:2]
            rate = data[row_mask][:, 2]
            g.add_edges(edges[:, 0], edges[:, 1])
            g.edata['h'] = rate.reshape(-1, 1)
            self.graphs.append(g) 
Example #14
Source File: fixedscaleoffset.py    From numcodecs with MIT License 6 votes vote down vote up
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # flatten to simplify implementation
        arr = arr.reshape(-1, order='A')

        # compute scale offset
        enc = (arr - self.offset) * self.scale

        # round to nearest integer
        enc = np.around(enc)

        # convert dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
Example #15
Source File: quantize.py    From numcodecs with MIT License 6 votes vote down vote up
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # apply scaling
        precision = 10. ** -self.digits
        exp = math.log(precision, 10)
        if exp < 0:
            exp = int(math.floor(exp))
        else:
            exp = int(math.ceil(exp))
        bits = math.ceil(math.log(10. ** -exp, 2))
        scale = 2. ** bits
        enc = np.around(scale * arr) / scale

        # cast dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
Example #16
Source File: test_alter_index.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_reindex_nearest():
    s = Series(np.arange(10, dtype='int64'))
    target = [0.1, 0.9, 1.5, 2.0]
    actual = s.reindex(target, method='nearest')
    expected = Series(np.around(target).astype('int64'), target)
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest')
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest', tolerance=1)
    assert_series_equal(expected, actual)
    actual = s.reindex_like(actual, method='nearest',
                            tolerance=[1, 2, 3, 4])
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest', tolerance=0.2)
    expected = Series([0, 1, np.nan, 2], target)
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest',
                       tolerance=[0.3, 0.01, 0.4, 3])
    expected = Series([0, np.nan, np.nan, 2], target)
    assert_series_equal(expected, actual) 
Example #17
Source File: sampler.py    From phoenics with Apache License 2.0 6 votes vote down vote up
def _proposal_optimization_thread(self, batch_index, return_dict = None):
		print('starting process for ', batch_index)
		# prepare penalty function
		def penalty(x):
			num, den = self.penalty_contributions(x)
			return (num + self.lambda_values[batch_index]) / den

		optimized = []
#		for sample in self.proposals:
#			if np.random.uniform() < 0.5:
#				optimized.append(sample)
#				continue
#			res = minimize(penalty, sample, method = 'L-BFGS-B', options = {'maxiter': 25})
#
#			# FIXME
#			if np.any(res.x < self.var_lows) or np.any(res.x > self.var_highs):
#				optimized.append(sample)
#			else:
#				optimized.append(res.x)
	
		for sample in self.proposals:

			# set some entries to zero!
			set_to_zero = self._gen_set_to_zero_vector(sample)
			nulls = np.where(set_to_zero == 0)[0]

			opt = self.local_opt.optimize(penalty, sample * set_to_zero, max_iter = 10, ignore = nulls)

			optimized.append(opt)


		optimized = np.array(optimized)
		optimized[:, self._ints] = np.around(optimized[:, self._ints])
		optimized[:, self._cats] = np.around(optimized[:, self._cats])

		print('finished process for ', batch_index)
		if return_dict.__class__.__name__ == 'DictProxy':
			return_dict[batch_index] = optimized
		else:
			return optimized 
Example #18
Source File: sampler.py    From phoenics with Apache License 2.0 6 votes vote down vote up
def _get_random_proposals(self, current_best, num_samples):
		# get uniform samples first
		uniform_samples = []
		for var_index, full_var_dict in enumerate(self.var_dicts):
			var_dict = full_var_dict[self.var_names[var_index]]
			sampled_values = self.random_number_generator.generate(var_dict, size = (self.var_sizes[var_index], self.total_size * num_samples))
			uniform_samples.extend(sampled_values)
		uniform_samples = np.array(uniform_samples).transpose()

		proposals = np.array(uniform_samples)

		num_narrows = int(0.25 * num_samples) + 1
		for sd in [0.03, 0.01, 0.003, 0.001, 0.0003]:
			# also get some samples around the current best
			# TODO: this only works for floats!!
			gauss_samples = current_best + np.random.normal(0., sd * self.var_p_ranges, size = (self.total_size * num_narrows, len(current_best)))
			gauss_samples = np.where(gauss_samples < self.var_p_lows, self.var_p_lows, gauss_samples)
			gauss_samples = np.where(self.var_p_highs < gauss_samples, self.var_p_highs, gauss_samples)

			proposals = np.concatenate([proposals, gauss_samples])
		return np.array(proposals) 
Example #19
Source File: tools.py    From buzzard with Apache License 2.0 6 votes vote down vote up
def make_tif(path, tloffset=(0, 0), reso=(0.25, -0.25), rsize=(20, 10),
             proj=SRS[0]['wkt'], channel_count=1, dtype=gdal.GDT_Float32):
    """Create a tiff files and return info about it"""
    tl = ROOT_TL + tloffset
    reso = np.asarray(reso)
    fp = buzz.Footprint(tl=tl, rsize=rsize, size=np.abs(reso * rsize))
    x, y = fp.meshgrid_spatial
    x = np.abs(x) - abs(ROOT_TL[0])
    y = abs(ROOT_TL[1]) - np.abs(y)
    x *= 15
    y *= 15
    a = x / 2 + y / 2
    a = np.around(a).astype('float32')
    driver = gdal.GetDriverByName('GTiff')
    dataset = driver.Create(path, rsize[0], rsize[1], channel_count, dtype)
    dataset.SetGeoTransform(fp.gt)
    dataset.SetProjection(proj)
    for i in range(channel_count):
        dataset.GetRasterBand(i + 1).WriteArray(a)
        dataset.GetRasterBand(i + 1).SetNoDataValue(-32000.)
    dataset.FlushCache()
    return path, fp, a 
Example #20
Source File: testutils.py    From recruit with Apache License 2.0 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #21
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None,
                                ndigits=5, unit='', stroke_width=1, fill_opacity=.9,
                                geojson_properties=None, strdump=False, serialize=True):
    """Transform matplotlib.contourf to geojson with overlapping filled contours."""
    polygon_features = []
    contourf_idx = 0
    contourf_levels = get_contourf_levels(contourf.levels, contourf.extend)
    for collection in contourf.collections:
        color = collection.get_facecolor()
        for path in collection.get_paths():
            for coord in path.to_polygons():
                if min_angle_deg:
                    coord = keep_high_angle(coord, min_angle_deg)
                coord = np.around(coord, ndigits) if ndigits else coord
                polygon = Polygon(coordinates=[coord.tolist()])
                fcolor = rgb2hex(color[0])
                properties = set_contourf_properties(stroke_width, fcolor, fill_opacity, contourf_levels[contourf_idx], unit)
                if geojson_properties:
                    properties.update(geojson_properties)
                feature = Feature(geometry=polygon, properties=properties)
                polygon_features.append(feature)
        contourf_idx += 1
    feature_collection = FeatureCollection(polygon_features)
    return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize) 
Example #22
Source File: phoenics.py    From phoenics with Apache License 2.0 5 votes vote down vote up
def choose(self, num_samples = None, observations = None, as_array = False):
		if not num_samples:
			num_samples = self.param_dict['general']['num_batches']

		if observations:
			# generating samples
			self._generate_sampled(num_samples, observations)		
			# get the most informative
			print('# selecting informative samples')
			self.imp_samples = self.sample_selector.select(num_samples, self.proposed_samples, self.network.penalty_contributions, self.network.lambda_values, self.characteristic_distances)
#			self.imp_samples = np.squeeze(self.imp_samples)
		else:
			# generating samples
			self._generate_uniform(num_samples * self.param_dict['general']['batch_size'])
			# cleaning samples - not required for uniform samples
#			self.imp_samples = np.squeeze(self.proposed_samples)
			self.imp_samples = self.proposed_samples

		# convert sampled parameters to list of dicts
		self.gen_samples = []
		for sample in self.imp_samples:
			sample_dict = {}
			lower, upper = 0, self.var_sizes[0]
			for var_index, var_name in enumerate(self.var_names):
				# we need to translate categories
				if self.var_types[var_index] == 'categorical':
					sample_dict[var_name] = {'samples': [self.var_options[var_index][int(np.around(element))] for element in sample[lower:upper]]}
				else:	
					sample_dict[var_name] = {'samples': sample[lower:upper]}
				if var_index == len(self.var_names) - 1:
					break
				lower = upper
				upper += self.var_sizes[var_index + 1]
			self.gen_samples.append(copy.deepcopy(sample_dict))

		if as_array:
			return self.imp_samples
		else:
			return self.gen_samples 
Example #23
Source File: test_numeric.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_round(self):
        arr = [1.56, 72.54, 6.35, 3.25]
        tgt = [1.6, 72.5, 6.4, 3.2]
        assert_equal(np.around(arr, decimals=1), tgt) 
Example #24
Source File: test_arithmetic_execution.py    From mars with Apache License 2.0 5 votes vote down vote up
def testAroundOrderExecution(self):
        data = np.asfortranarray(np.random.rand(10, 20))
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data, decimals=2)

        np.testing.assert_allclose(res, expected)
        self.assertTrue(res.flags['F_CONTIGUOUS'])
        self.assertFalse(res.flags['C_CONTIGUOUS']) 
Example #25
Source File: dashboard.py    From crappy with GNU General Public License v2.0 5 votes vote down vote up
def main(self):
    """
    Main loop.
    """
    if not self.labels:
      self.labels = list(self.inputs[0].recv(blocking=True).keys())
      self.nb_display_values = len(self.labels)
    dash_thread = threading.Thread(target=self.Dashboard,
                                   args=(self.labels, self.nb_digits,
                                         self.queue))
    dash_thread.daemon = True
    dash_thread.start()
    list_to_show = []
    while True:
      data_received = self.inputs[0].recv(blocking=True)
      if len(self.labels) == len(data_received):
        time = np.mean(list(data_received.values())[0])
        values = [np.mean(list(data_received.values())[label]) for label in
                  range(1, self.nb_display_values)]
        list_to_show.append(time)
        list_to_show.extend(values)
      else:
        for label in self.labels:
          list_to_show.append(
            np.around(np.mean(data_received[label]), self.nb_digits))
      self.queue.put(list_to_show)
      list_to_show = [] 
Example #26
Source File: multipoly.py    From geojsoncontour with MIT License 5 votes vote down vote up
def __init__(self, path_collection, min_angle_deg, ndigits):
        self.coords = []
        for path in path_collection.get_paths():
            polygon = []
            for linestring in path.to_polygons():
                if min_angle_deg:
                    linestring = keep_high_angle(linestring, min_angle_deg)
                if ndigits:
                    linestring = np.around(linestring, ndigits)
                polygon.append(linestring.tolist())
            self.coords.append(polygon) 
Example #27
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None,
                       ndigits=5, unit='', stroke_width=1, geojson_properties=None, strdump=False,
                       serialize=True):
    """Transform matplotlib.contour to geojson."""
    collections = contour.collections
    contour_index = 0
    line_features = []
    for collection in collections:
        color = collection.get_edgecolor()
        for path in collection.get_paths():
            v = path.vertices
            if len(v) < 3:
                continue
            coordinates = keep_high_angle(v, min_angle_deg) if min_angle_deg else v
            coordinates = np.around(coordinates, ndigits) if ndigits is not None else coordinates
            line = LineString(coordinates.tolist())
            properties = {
                "stroke-width": stroke_width,
                "stroke": rgb2hex(color[0]),
                "title": "%.2f" % contour.levels[contour_index] + ' ' + unit,
                "level-value": float("%.6f" % contour.levels[contour_index]),
                "level-index": contour_index
            }
            if geojson_properties:
                properties.update(geojson_properties)
            line_features.append(Feature(geometry=line, properties=properties))
        contour_index += 1
    feature_collection = FeatureCollection(line_features)
    return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize) 
Example #28
Source File: plotting.py    From pmf-automl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compare_ranks(regrets, num_decimals=10):

    all_results = np.stack([regrets[k] for k in regrets.keys()], axis=2)
    all_results = np.around(all_results, num_decimals)
    ranks0 = np.apply_along_axis(st.rankdata, 2, all_results)
    ranks = {}
    for i in range(len(regrets.keys())):
        ranks[list(regrets.keys())[i]] = ranks0[:,:,i].squeeze()

    n_evals = regrets[list(regrets.keys())[0]].shape[0]
    plot_comparison(n_evals, ranks)
    plt.ylabel('Rank (mean $\pm$ SE)')
    plt.show() 
Example #29
Source File: gym_env.py    From tensor2tensor with Apache License 2.0 5 votes vote down vote up
def step(self, actions):
    """Makes a step in all environments.

    Does any preprocessing and records frames.

    Args:
      actions: Batch of actions.

    Returns:
      (obs, rewards, dones) - batches of observations, rewards and done flags
      respectively.

    Raises:
      ValueError: when the data for current epoch has already been loaded.
    """
    if self._store_rollouts and \
        self._rollouts_by_epoch_and_split[self.current_epoch]:
      raise ValueError(
          "Data for current epoch has already been loaded from disk."
      )
    (obs, unclipped_rewards, dones) = self._step(actions)
    obs = self._preprocess_observations(obs)
    (min_reward, max_reward) = self.reward_range
    rewards = np.around(np.clip(unclipped_rewards, min_reward, max_reward))
    if self._store_rollouts:
      unclipped_rewards = unclipped_rewards.astype(np.float64)
      encoded_obs = self._encode_observations(obs)
      for (rollout, frame, action) in zip(
          self._current_batch_rollouts, self._current_batch_frames, actions
      ):
        rollout.append(frame._replace(action=action))

      # orud = (observation, reward, unclipped_reward, done)
      self._current_batch_frames = [
          Frame(*orud, action=None)
          for orud in zip(encoded_obs, rewards, unclipped_rewards, dones)
      ]
    return (obs, rewards, dones) 
Example #30
Source File: gang_trainer.py    From HyperGAN with MIT License 5 votes vote down vote up
def crossover(self, s1, s2):
        strat = list(s1)
        for i,layer in enumerate(s2):
            mask = np.random.rand(*layer.shape)
            if self.config.crossover_random == None:
                mask = np.around(mask)
            strat[i]=mask*layer + (1-mask)*strat[i]
        return strat