Python numpy.put() Examples
The following are 30
code examples of numpy.put().
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: builder.py From actionable-recourse with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, action_set, x = None, **kwargs): self.built = False #setup the optimizer here: self._optimizer = SolverFactory('cbc') self._results = None #todo: Alex fill out these functions ## todo: check what each of these does in CPLEX. self._set_mip_time_limit = lambda mip, time_limit: True #_set_mip_time_limit(self, mip, time_limit) self._set_mip_node_limit = lambda mip, node_limit: True #_set_mip_node_limit(self, mip, node_limit) ## todo: not sure what to put for this. let's talk about what the cplex display flag does. self._set_mip_display = lambda mip, display_flag: True #_set_mip_display(self, mip, display) self._apriori_infeasible = False super().__init__(action_set = action_set, x = x, **kwargs) #### building MIP ####
Example #2
Source File: reduce.py From biskit with GNU General Public License v3.0 | 6 votes |
def merge( self, inmodel=None ): """ Rescue profiles and info records from input model into result model. """ r = self.result.clone() m = inmodel or self.model i1, i2 = r.compareAtoms( m ) mask1 = N.zeros( len( r ), N.int ) N.put( mask1, i1, 1 ) r.atoms.update( m.atoms, mask=mask1 ) r.fileName = m.fileName r.source = m.source return r
Example #3
Source File: insert.py From cupy with MIT License | 6 votes |
def put(a, ind, v, mode='wrap'): """Replaces specified elements of an array with given values. Args: a (cupy.ndarray): Target array. ind (array-like): Target indices, interpreted as integers. v (array-like): Values to place in `a` at target indices. If `v` is shorter than `ind` it will be repeated as necessary. mode (str): How out-of-bounds indices will behave. Its value must be either `'raise'`, `'wrap'` or `'clip'`. Otherwise, :class:`TypeError` is raised. .. note:: Default `mode` is set to `'wrap'` to avoid unintended performance drop. If you need NumPy's behavior, please pass `mode='raise'` manually. .. seealso:: :func:`numpy.put` """ a.put(ind, v, mode=mode)
Example #4
Source File: document_embedder.py From fake-news-detection-pipeline with Apache License 2.0 | 6 votes |
def get_onehot_arr(place, dim, put_value=1.): """ get a `dim` dimensional one-hot vector, with `place`-th entry being `put_value` and dtype being np.float32 e.g.: >>> get_onehot_arr(3, 5, 1.3) np.ndarray([0, 0, 0, 1.3, 0], dtype=np.float32) :param place: the place to put a non-zero value :param dim: the length of the vector :param put_value: the value to be put :return: a `dim` dimensional one-hot vector, with `place`-th entry being `put_value` and dtype being np.float32 """ if place >= dim or place < 0: print("Invalid input: place = {}, dim = {}".format(place, dim)) ans = np.zeros(dim, dtype=np.float32) np.put(ans, place, put_value) return ans
Example #5
Source File: parameter_core.py From paramz with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _transform_gradients(self, g): """ Transform the gradients by multiplying the gradient factor for each constraint to it. """ #py3 fix #[np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__] [np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.items() if c != __fixed__] if self._has_fixes(): return g[self._fixes_] return g #def _transform_gradients_non_natural(self, g): # """ # Transform the gradients by multiplying the gradient factor for each # constraint to it, using the theta transformed natural gradient. # """ # #py3 fix # #[np.put(g, i, c.gradfactor_non_natural(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__] # [np.put(g, i, c.gradfactor_non_natural(self.param_array[i], g[i])) for c, i in self.constraints.items() if c != __fixed__] # if self._has_fixes(): return g[self._fixes_] # return g
Example #6
Source File: MEC.py From SDA with MIT License | 6 votes |
def readCuts(myfile): cuts = open(myfile).readlines() haps = np.zeros((len(cuts), m)) totalPSVs = 0 for idx, psvs in enumerate(cuts): psvs=psvs.strip().split() psvs = map(int, psvs) for psv in psvs: psvPositions.append(psv) np.put(haps[idx], psvs, [1]) totalPSVs += len(psvs) # get rid of positions where there are two PSVs at one stop # not sure why this happens, will Have to fix with mark # confirmed as a bug, a fix is in the works # hack to skip it for now toRm = list(np.where( (haps.sum(axis = 0) > 1) )[0]) for pos in toRm: print("mulitple PSVs in one spot!") psvPositions.remove(pos) return(haps)
Example #7
Source File: rcv1.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def _inverse_permutation(p): """inverse permutation p""" n = p.size s = np.zeros(n, dtype=np.int32) i = np.arange(n, dtype=np.int32) np.put(s, p, i) # s[p] = i return s
Example #8
Source File: dataset.py From VietnameseOCR with Apache License 2.0 | 5 votes |
def to_one_hot(self, X): one_hot = np.zeros((len(X), NO_LABEL)) for i in range(len(X)): np.put(one_hot[i, :], X[i], 1) return one_hot
Example #9
Source File: insert.py From cupy with MIT License | 5 votes |
def place(arr, mask, vals): """Change elements of an array based on conditional and input values. This function uses the first N elements of `vals`, where N is the number of true values in `mask`. Args: arr (cupy.ndarray): Array to put data into. mask (array-like): Boolean mask array. Must have the same size as `a`. vals (array-like): Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) .. warning:: This function may synchronize the device. .. seealso:: :func:`numpy.place` """ # TODO(niboshi): Avoid nonzero which may synchronize the device. mask = cupy.asarray(mask) if arr.size != mask.size: raise ValueError('Mask and data must be the same size.') vals = cupy.asarray(vals) mask_indices = mask.ravel().nonzero()[0] # may synchronize if mask_indices.size == 0: return if vals.size == 0: raise ValueError('Cannot insert from an empty array.') arr.put(mask_indices, vals, mode='wrap')
Example #10
Source File: lmdd.py From pyod with BSD 2-Clause "Simplified" License | 5 votes |
def __sf(self, X): """Internal function to calculate for Smoothing Factors of data points Repeated n_iter_ of times in randomized mode. """ dis_ = np.zeros(shape=(X.shape[0],)) card_ = np.zeros(shape=(X.shape[0],)) # perform one process with the original input order itr_res = self.__dis(X) np.put(card_, X.shape[0] - sum([i > 0. for i in itr_res]), np.where(itr_res > 0.)) # create a copy of random state to preserve original state for # future fits (if any) random_state = np.random.RandomState( seed=self.random_state_.get_state()[1][0]) indices = np.arange(X.shape[0]) for _ in range(self.n_iter_): ind_ = indices random_state.shuffle(ind_) _x = X[indices] # get dissimilarity of this iteration and restore original order itr_res = self.__dis(_x)[np.argsort(ind_)] current_card = X.shape[0] - sum([i > 0. for i in itr_res]) # compare with previous iteration to get the maximal dissimilarity for i, j in enumerate(itr_res): if j > dis_[i]: dis_[i] = j card_[i] = current_card # Increase random state seed by one to reorder input next iteration random_state.seed(random_state.get_state()[1][0] + 1) return np.multiply(dis_, card_)
Example #11
Source File: rcv1.py From twitter-stock-recommendation with MIT License | 5 votes |
def _inverse_permutation(p): """inverse permutation p""" n = p.size s = np.zeros(n, dtype=np.int32) i = np.arange(n, dtype=np.int32) np.put(s, p, i) # s[p] = i return s
Example #12
Source File: np_conserved.py From tenpy with GNU General Public License v3.0 | 5 votes |
def diag(s, leg, dtype=None, labels=None): """Returns a square, diagonal matrix of entries `s`. The resulting matrix has legs ``(leg, leg.conj())`` and charge 0. Parameters ---------- s : scalar | 1D array The entries to put on the diagonal. If scalar, all diagonal entries are the same. leg : :class:`LegCharge` The first leg of the resulting matrix. dtype : None | type The data type to be used for the result. By default, use dtype of `s`. labels : list of {str | None} Labels associated to each leg, ``None`` for non-named labels. Returns ------- diagonal : :class:`Array` A square matrix with diagonal entries `s`. See also -------- Array.scale_axis : similar as ``tensordot(diag(s), ...)``, but faster. """ s = np.asarray(s, dtype) scalar = (s.ndim == 0) if not scalar and len(s) != leg.ind_len: raise ValueError("len(s)={0:d} not equal to leg.ind_len={1:d}".format(len(s), leg.ind_len)) res = Array((leg, leg.conj()), s.dtype, labels=labels) # default charge is 0 # qdata = [[0, 0], [1, 1], ....] res._qdata = np.arange(leg.block_number, dtype=np.intp)[:, np.newaxis] * np.ones(2, np.intp) # ``res._qdata_sorted = True`` was already set if scalar: res._data = [np.diag(s * np.ones(size, dtype=s.dtype)) for size in leg.get_block_sizes()] else: res._data = [np.diag(s[leg.get_slice(qi)]) for qi in range(leg.block_number)] return res
Example #13
Source File: PatchGenerator.py From biskit with GNU General Public License v3.0 | 5 votes |
def patchAround( self, atom, size ): """ patchAround( int_atom, int_nAtoms ) -> mask for self.model Create single patch of given size around given atom """ dist = self.__distances( atom ) order = N.argsort( dist ) r = N.zeros( len( self.model ), 'i' ) N.put( r, order[:size], 1 ) return r
Example #14
Source File: polymer.py From biskit with GNU General Public License v3.0 | 5 votes |
def modelMask( self ): """ Create a mask for parent Polymer, marking every position covered by this feature. @return: @rtype: N.array of int or bool """ r = N.zeros( len( self.model ) ) N.put( r, self.map, 1 ) return r
Example #15
Source File: parameter_core.py From paramz with BSD 3-Clause "New" or "Revised" License | 5 votes |
def optimizer_array(self): """ Array for the optimizer to work on. This array always lives in the space for the optimizer. Thus, it is untransformed, going from Transformations. Setting this array, will make sure the transformed parameters for this model will be set accordingly. It has to be set with an array, retrieved from this method, as e.g. fixing will resize the array. The optimizer should only interfere with this array, such that transformations are secured. """ if self.__dict__.get('_optimizer_copy_', None) is None or self.size != self._optimizer_copy_.size: self._optimizer_copy_ = np.empty(self.size) if not self._optimizer_copy_transformed: self._optimizer_copy_.flat = self.param_array.flat #py3 fix #[np.put(self._optimizer_copy_, ind, c.finv(self.param_array[ind])) for c, ind in self.constraints.iteritems() if c != __fixed__] [np.put(self._optimizer_copy_, ind, c.finv(self.param_array[ind])) for c, ind in self.constraints.items() if c != __fixed__] self._optimizer_copy_transformed = True if self._has_fixes():# or self._has_ties()): self._ensure_fixes() return self._optimizer_copy_[self._fixes_] return self._optimizer_copy_
Example #16
Source File: parameter_core.py From paramz with BSD 3-Clause "New" or "Revised" License | 5 votes |
def optimizer_array(self, p): """ Make sure the optimizer copy does not get touched, thus, we only want to set the values *inside* not the array itself. Also we want to update param_array in here. """ f = None if self.has_parent() and self.constraints[__fixed__].size != 0: f = np.ones(self.size).astype(bool) f[self.constraints[__fixed__]] = FIXED elif self._has_fixes(): f = self._fixes_ if f is None: self.param_array.flat = p [np.put(self.param_array, ind, c.f(self.param_array.flat[ind])) #py3 fix #for c, ind in self.constraints.iteritems() if c != __fixed__] for c, ind in self.constraints.items() if c != __fixed__] else: self.param_array.flat[f] = p [np.put(self.param_array, ind[f[ind]], c.f(self.param_array.flat[ind[f[ind]]])) #py3 fix #for c, ind in self.constraints.iteritems() if c != __fixed__] for c, ind in self.constraints.items() if c != __fixed__] #self._highest_parent_.tie.propagate_val() self._optimizer_copy_transformed = False self.trigger_update()
Example #17
Source File: loss.py From LightNet with MIT License | 5 votes |
def unique_encode(self, cls_targets): batch_size, _, _ = cls_targets.size() target_mask = (cls_targets >= 0) * (cls_targets != self.ignore_label) cls_targets = [cls_targets[idx].masked_select(target_mask[idx]) for idx in np.arange(batch_size)] # unique_cls = [np.unique(label.numpy(), return_counts=True) for label in cls_targets] unique_cls = [np.unique(label.numpy()) for label in cls_targets] encode = np.zeros((batch_size, self.num_classes), dtype=np.uint8) for idx in np.arange(batch_size): np.put(encode[idx], unique_cls[idx], 1) return torch.from_numpy(encode).float()
Example #18
Source File: setdiag0.py From emotion-classification with MIT License | 5 votes |
def setdiag0(K): """Set the diagonal entries of a square matrix to 0 """ n = K.shape[0] numpy.put(K, numpy.arange(n) * (n + 1), 0.0)
Example #19
Source File: lane_keeping_env.py From highway-env with MIT License | 5 votes |
def store_data(self) -> None: if self.lpv: state = self.vehicle.state.copy() interval = [] for x_t in self.lpv.change_coordinates(self.lpv.x_i_t, back=True, interval=True): # lateral state to full state np.put(state, [1, 2, 4, 5], x_t) # full state to absolute coordinates interval.append(state.squeeze(-1).copy()) self.interval_trajectory.append(interval) self.trajectory.append(copy.deepcopy(self.vehicle.state))
Example #20
Source File: GC_script.py From ClimateVegetationDynamics_GrangerCausality with GNU General Public License v3.0 | 5 votes |
def shift2(arr,num): arr=np.roll(arr,num) if num < 0: np.put(arr,range(len(arr)+num,len(arr)),np.nan) elif num > 0: np.put(arr,range(num),np.nan) return arr #parameters: string 'inpath' which is the path of the .csv dataset #returns: the dataset in a numpy array
Example #21
Source File: ssd.py From bluesky with GNU General Public License v3.0 | 5 votes |
def qdrdist_matrix_indices(self, ntraf): """ This function gives the indices that can be used in the lon/lat-vectors """ # The indices will be n*(n-1)/2 long # Only works for n >= 2, which is logical... # This is faster than np.triu_indices :) tmp_range = np.arange(ntraf - 1, dtype=np.int32) ind1 = np.repeat(tmp_range, (tmp_range + 1)[::-1]) ind2 = np.ones(ind1.shape[0], dtype=np.int32) inds = np.cumsum(tmp_range[1:][::-1] + 1) np.put(ind2, inds, np.arange(ntraf * -1 + 3, 1)) ind2 = np.cumsum(ind2, out=ind2) return ind1, ind2
Example #22
Source File: rcv1.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def _inverse_permutation(p): """inverse permutation p""" n = p.size s = np.zeros(n, dtype=np.int32) i = np.arange(n, dtype=np.int32) np.put(s, p, i) # s[p] = i return s
Example #23
Source File: test_cfproto.py From alibi with Apache License 2.0 | 5 votes |
def test_tf_keras_iris_explainer(tf_keras_iris_explainer, use_kdtree, k): X_train, model, cf = tf_keras_iris_explainer # instance to be explained x = X_train[0].reshape(1, -1) pred_class = np.argmax(model.predict(x)) not_pred_class = np.argmin(model.predict(x)) # test fit cf.fit(X_train) if use_kdtree: # k-d trees assert len(cf.kdtrees) == cf.classes # each class has a k-d tree n_by_class = 0 for c in range(cf.classes): n_by_class += cf.X_by_class[c].shape[0] assert n_by_class == X_train.shape[0] # all training instances are stored in the trees assert cf.kdtrees[pred_class].query(x, k=1)[0] == 0. # nearest distance to own class equals 0 assert cf.score(x, not_pred_class, pred_class) == 0. # test score fn else: # encoder assert len(list(cf.class_proto.keys())) == cf.classes assert [True for _ in range(cf.classes)] == [v.shape == (1, 2) for _, v in cf.class_proto.items()] n_by_class = 0 for c in range(cf.classes): n_by_class += cf.class_enc[c].shape[0] assert n_by_class == X_train.shape[0] # all training instances encoded # test explanation explanation = cf.explain(x, k=k) assert cf.id_proto != pred_class assert np.argmax(model.predict(explanation.cf['X'])) == explanation.cf['class'] assert explanation.cf['grads_num'].shape == explanation.cf['grads_graph'].shape == x.shape assert explanation.meta.keys() == DEFAULT_META_CFP.keys() assert explanation.data.keys() == DEFAULT_DATA_CFP.keys() # test gradient shapes y = np.zeros((1, cf.classes)) np.put(y, pred_class, 1) cf.predict = cf.predict.predict # make model black box grads = cf.get_gradients(x, y, x.shape[1:]) assert grads.shape == x.shape
Example #24
Source File: test_processbase.py From echopype with Apache License 2.0 | 5 votes |
def test_remove_noise(): # Create process object tmp = ConvertEK60(ek60_raw_path) tmp.raw2nc() e_data = Process(tmp.nc_path) freq, npings, nrange = [100000], 2, 100 ping_index = np.arange(npings) range_bin = np.arange(nrange) # Test noise rsemoval on upside-down parabola data = np.ones(nrange) # Insert noise points np.put(data, 30, -30) np.put(data, 60, -30) # Add more pings data = np.array([data] * npings) # Make DataArray Sv = xr.DataArray([data], coords=[('frequency', freq), ('ping_time', ping_index), ('range_bin', range_bin)]) Sv.name = "Sv" ds = Sv.to_dataset() e_data.Sv = ds # Create range, and seawater_absorption needed for noise_removal e_data.sample_thickness = xr.DataArray([0.1], coords=[('frequency', freq)]) e_data._range = e_data.sample_thickness * \ xr.DataArray([np.arange(nrange)], coords=[('frequency', freq), ('range_bin', np.arange(nrange))]) e_data._seawater_absorption = xr.DataArray([0.1], coords=[('frequency', freq)]) # Run noise removal e_data.remove_noise() # Test if noise points are are nan assert np.isnan(e_data.Sv_clean.Sv[0][0][30]) assert np.isnan(e_data.Sv_clean.Sv[0][0][60]) # delete created nc file os.remove(tmp.nc_path)
Example #25
Source File: StockTradingEnv.py From Stock-Trading-Visualization with MIT License | 5 votes |
def _next_observation(self): frame = np.zeros((5, LOOKBACK_WINDOW_SIZE + 1)) # Get the stock data points for the last 5 days and scale to between 0-1 np.put(frame, [0, 4], [ self.df.loc[self.current_step: self.current_step + LOOKBACK_WINDOW_SIZE, 'Open'].values / MAX_SHARE_PRICE, self.df.loc[self.current_step: self.current_step + LOOKBACK_WINDOW_SIZE, 'High'].values / MAX_SHARE_PRICE, self.df.loc[self.current_step: self.current_step + LOOKBACK_WINDOW_SIZE, 'Low'].values / MAX_SHARE_PRICE, self.df.loc[self.current_step: self.current_step + LOOKBACK_WINDOW_SIZE, 'Close'].values / MAX_SHARE_PRICE, self.df.loc[self.current_step: self.current_step + LOOKBACK_WINDOW_SIZE, 'Volume'].values / MAX_NUM_SHARES, ]) # Append additional data and scale each value to between 0-1 obs = np.append(frame, [ [self.balance / MAX_ACCOUNT_BALANCE], [self.max_net_worth / MAX_ACCOUNT_BALANCE], [self.shares_held / MAX_NUM_SHARES], [self.cost_basis / MAX_SHARE_PRICE], [self.total_sales_value / (MAX_NUM_SHARES * MAX_SHARE_PRICE)], ], axis=1) return obs
Example #26
Source File: limits.py From numdifftools with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _call_lim(self, fz, z, f): err = np.zeros_like(fz) final_step = np.zeros_like(fz) index = np.zeros_like(fz, dtype=int) k = np.flatnonzero(np.isnan(fz)) if k.size > 0: fz = np.where(np.isnan(fz), 0, fz) lim_fz, info1 = self._lim(f, z.flat[k]) np.put(fz, k, lim_fz) if self.full_output: np.put(final_step, k, info1.final_step) np.put(index, k, info1.index) np.put(err, k, info1.error_estimate) return fz, self.info(err, final_step, index)
Example #27
Source File: mmlwrapper.py From polara with MIT License | 5 votes |
def _remap_factors(entity_mapping, entity_factors, num_entities, num_factors): shape = (num_entities, num_factors) entity_id = np.repeat(entity_mapping.loc[:, 1].values, num_factors, axis=0).astype(np.int64) factor_id = entity_factors['col2'].values.astype(np.int64) entity_factors_idx = np.ravel_multi_index((entity_id, factor_id), dims=shape) entity_factors_new = np.zeros(shape) np.put(entity_factors_new, entity_factors_idx, entity_factors['col3'].values) return entity_factors_new
Example #28
Source File: test_utils.py From graspy with Apache License 2.0 | 5 votes |
def setUpClass(cls): # simple ERxN graph n = 15 p = 0.5 cls.A = np.zeros((n, n)) nedge = int(round(n * n * p)) np.put( cls.A, np.random.choice(np.arange(0, n * n), size=nedge, replace=False), np.random.normal(size=nedge), )
Example #29
Source File: test_io.py From graspy with Apache License 2.0 | 5 votes |
def setup_class(cls): # simple ERxN graph n = 15 p = 0.5 cls.A = np.zeros((n, n)) nedge = int(round(n * n * p)) np.put( cls.A, np.random.choice(np.arange(0, n * n), size=nedge, replace=False), np.random.normal(size=nedge), )
Example #30
Source File: test_utils.py From graspy with Apache License 2.0 | 5 votes |
def setUpClass(cls): # simple ERxN graph n = 15 p = 0.5 cls.A = np.zeros((n, n)) nedge = int(round(n * n * p)) np.put( cls.A, np.random.choice(np.arange(0, n * n), size=nedge, replace=False), np.random.normal(size=nedge), )