Python numpy.asscalar() Examples
The following are 30
code examples of numpy.asscalar().
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: imagenet.py From vergeml with MIT License | 7 votes |
def predict(self, f, k=5, resize_mode='fill'): from keras.preprocessing import image from vergeml.img import resize_image filename = os.path.basename(f) if not os.path.exists(f): return dict(filename=filename, prediction=[]) img = image.load_img(f) img = resize_image(img, self.image_size, self.image_size, 'antialias', resize_mode) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = self.preprocess_input(x) preds = self.model.predict(x) pred = self._decode(preds, top=k)[0] prediction=[dict(probability=np.asscalar(perc), label=klass) for _, klass, perc in pred] return dict(filename=filename, prediction=prediction)
Example #2
Source File: test_data.py From dket with GNU General Public License v3.0 | 6 votes |
def test_parse(self): """Base test for the `dket.data.decode` function.""" words = [1, 2, 3, 0] formula = [12, 23, 34, 45, 0] example = data.encode(words, formula) serialized = example.SerializeToString() words_t, sent_len_t, formula_t, form_len_t = data.parse(serialized) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) actual = sess.run([words_t, sent_len_t, formula_t, form_len_t]) self.assertEqual(words, actual[0].tolist()) self.assertEqual(len(words), np.asscalar(actual[1])) self.assertEqual(formula, actual[2].tolist()) self.assertEqual(len(formula), np.asscalar(actual[3]))
Example #3
Source File: transforms.py From pase with MIT License | 6 votes |
def __call__(self, wav, srate=16000, nbits=16): """ Add noise to clean wav """ if isinstance(wav, torch.Tensor): wav = wav.numpy() noise_idx = np.random.choice(list(range(len(self.noises))), 1) sel_noise = self.noises[np.asscalar(noise_idx)] noise = sel_noise['data'] snr = np.random.choice(self.snr_levels, 1) # print('Applying SNR: {} dB'.format(snr[0])) if wav.ndim > 1: wav = wav.reshape((-1,)) noisy, noise_bound = self.addnoise_asl(wav, noise, srate, nbits, snr, do_IRS=self.do_IRS) # normalize to avoid clipping if np.max(noisy) >= 1 or np.min(noisy) < -1: small = 0.1 while np.max(noisy) >= 1 or np.min(noisy) < -1: noisy = noisy / (1. + small) small = small + 0.1 return torch.FloatTensor(noisy.astype(np.float32))
Example #4
Source File: rfsm.py From pysheds with GNU General Public License v3.0 | 6 votes |
def set_cumulative_capacities(self, node): if node.l: self.set_cumulative_capacities(node.l) if node.r: self.set_cumulative_capacities(node.r) if node.parent: if node.name: elevdiff = node.parent.elev - self.dem[self.ws[node.level] == node.name] vol = abs(np.asscalar(elevdiff[elevdiff > 0].sum()) * self.x * self.y) node.vol = vol else: leaves = [] self.enumerate_leaves(node, level=node.level, stack=leaves) mask = np.isin(self.ws[node.level], leaves) boundary = list(chain.from_iterable([self.b[node.level].setdefault(pair, []) for pair in combinations(leaves, 2)])) mask.flat[boundary] = True elevdiff = node.parent.elev - self.dem[mask] vol = abs(np.asscalar(elevdiff[elevdiff > 0].sum()) * self.x * self.y) node.vol = vol
Example #5
Source File: cost.py From ilqr with GNU General Public License v3.0 | 6 votes |
def l(self, x, u, i, terminal=False): """Instantaneous cost function. Args: x: Current state [state_size]. u: Current control [action_size]. None if terminal. i: Current time step. terminal: Compute terminal cost. Default: False. Returns: Instantaneous cost (scalar). """ if terminal: return np.asscalar(self._l_term(x, i)) return np.asscalar(self._l(x, u, i))
Example #6
Source File: swmm.py From pysheds with GNU General Public License v3.0 | 6 votes |
def generate_storage_uncontrolled(self, ixes, **kwargs): storage_uncontrolled = {} depths = 4 init_depths = 0.1 storage_ends = [np.asscalar(self.endnodes[np.where(self.startnodes == ix)]) for ix in ixes] storage_uncontrolled['name'] = 'ST' + pd.Series(ixes).astype(str) storage_uncontrolled['elev'] = self.grid.view(self.dem).flat[storage_ends] storage_uncontrolled['ymax'] = self.channel_d.flat[ixes] + 1 storage_uncontrolled['y0'] = 0 storage_uncontrolled['Acurve'] = 'FUNCTIONAL' storage_uncontrolled['A0'] = self.channel_w.flat[ixes] storage_uncontrolled['A1'] = 0 storage_uncontrolled['A2'] = 1 storage_uncontrolled = pd.DataFrame.from_dict(storage_uncontrolled) # Manual overrides for key, value in kwargs.items(): storage_uncontrolled[key] = value self.storage_uncontrolled = storage_uncontrolled[['name', 'elev', 'ymax', 'y0', 'Acurve', 'A1', 'A2', 'A0']]
Example #7
Source File: swmm.py From pysheds with GNU General Public License v3.0 | 6 votes |
def generate_storage_controlled(self, ixes, **kwargs): storage_controlled = {} depths = 2 init_depths = 0.1 storage_ends = [np.asscalar(self.endnodes[np.where(self.startnodes == ix)]) for ix in ixes] storage_controlled['name'] = 'C' + pd.Series(ixes).astype(str) storage_controlled['elev'] = self.grid.view(self.dem).flat[storage_ends] storage_controlled['ymax'] = depths storage_controlled['y0'] = 0 storage_controlled['Acurve'] = 'FUNCTIONAL' storage_controlled['A0'] = 1000 storage_controlled['A1'] = 10000 storage_controlled['A2'] = 1 storage_controlled = pd.DataFrame.from_dict(storage_controlled) # Manual overrides for key, value in kwargs.items(): storage_controlled[key] = value self.storage_controlled = storage_controlled[['name', 'elev', 'ymax', 'y0', 'Acurve', 'A1', 'A2', 'A0']]
Example #8
Source File: cost.py From ilqr with GNU General Public License v3.0 | 6 votes |
def l(self, x, u, i, terminal=False): """Instantaneous cost function. Args: x: Current state [state_size]. u: Current control [action_size]. None if terminal. i: Current time step. terminal: Compute terminal cost. Default: False. Returns: Instantaneous cost (scalar). """ if terminal: z = np.hstack([x, i]) return np.asscalar(self._l_terminal(*z)) z = np.hstack([x, u, i]) return np.asscalar(self._l(*z))
Example #9
Source File: arrays.py From trax with Apache License 2.0 | 6 votes |
def __index__(self): """Returns a python scalar. This allows using an instance of this class as an array index. Note that only arrays of integer types with size 1 can be used as array indices. Returns: A Python scalar. Raises: TypeError: If the array is not of an integer type. ValueError: If the array does not have size 1. """ # TODO(wangpeng): Handle graph mode return np.asscalar(self.data.numpy())
Example #10
Source File: Multi-GPU_Training.py From tutorials with Apache License 2.0 | 6 votes |
def accuracy(model): accuracy = [] prefix = model.net.Proto().name for device in model._devices: accuracy.append( np.asscalar(workspace.FetchBlob("gpu_{}/{}_accuracy".format(device, prefix)))) return np.average(accuracy) # In[ ]: # SOLUTION for Part 11 # Start looping through epochs where we run the batches of images to cover the entire dataset # Usually you would want to run a lot more epochs to increase your model's accuracy
Example #11
Source File: Multi-GPU_Training.py From tutorials with Apache License 2.0 | 6 votes |
def accuracy(model): accuracy = [] prefix = model.net.Proto().name for device in model._devices: accuracy.append( np.asscalar(workspace.FetchBlob("gpu_{}/{}_accuracy".format(device, prefix)))) return np.average(accuracy) # ## Part 11: Run Multi-GPU Training and Get Test Results # You've come a long way. Now is the time to see it all pay off. Since you already ran ResNet once, you can glance at the code below and run it. The big difference this time is your model is parallelized! # # The additional components at the end deal with accuracy so you may want to dig into those specifics as a bonus task. You can try it again: just adjust the `num_epochs` value below, run the block, and see the results. You can also go back to Part 10 to reinitialize the model, and run this step again. (You may want to add `workspace.ResetWorkspace()` before you run the new models again.) # # Go back and check the images/sec from when you ran single GPU. Note how you can scale up with a small amount of overhead. # # ### Task: How many GPUs would it take to train ImageNet in under a minute? # In[ ]: # Start looping through epochs where we run the batches of images to cover the entire dataset # Usually you would want to run a lot more epochs to increase your model's accuracy
Example #12
Source File: metric.py From connecting_the_dots with MIT License | 6 votes |
def add(self, es, ta, ma=None): if ma is not None: raise Exception('mask is not implemented') es = es.ravel() ta = ta.ravel() if es.shape[0] != ta.shape[0]: raise Exception('invalid shape of es, or ta') if es.min() < 0 or es.max() > 1: raise Exception('estimate has wrong value range') ta_p = (ta == 1) ta_n = (ta == 0) es_p = es[ta_p] es_n = es[ta_n] for idx, wp in enumerate(self.thresholds): wp = np.asscalar(wp) self.tps[idx] += (es_p > wp).sum() self.fps[idx] += (es_n > wp).sum() self.fns[idx] += (es_p <= wp).sum() self.tns[idx] += (es_n <= wp).sum() self.n_pos += ta_p.sum() self.n_neg += ta_n.sum()
Example #13
Source File: core.py From calfem-python with MIT License | 6 votes |
def bar2e(ex,ey,ep): """ Compute the element stiffness matrix for two dimensional bar element. :param list ex: element x coordinates [x1, x2] :param list ey: element y coordinates [y1, y2] :param list ep: [E, A]: E - Young's modulus, A - Cross section area :return mat Ke: stiffness matrix, [4 x 4] """ E=ep[0] A=ep[1] b = np.mat([[ex[1]-ex[0]],[ey[1]-ey[0]]]) L = np.asscalar(np.sqrt(b.T*b)) Kle = np.mat([[1.,-1.],[-1.,1.]])*E*A/L n = np.asarray(b.T/L).reshape(2,) G = np.mat([ [n[0],n[1],0.,0.], [0.,0.,n[0],n[1]] ]) return G.T*Kle*G
Example #14
Source File: in_memory_eval.py From training_results_v0.5 with Apache License 2.0 | 6 votes |
def end(self, session): # pylint: disable=unused-argument """Runs evaluator for final model.""" # Only runs eval at the end if highest accuracy so far # is less than self._stop_threshold. if not self._run_success: step = np.asscalar(session.run(self._global_step_tensor)) logging.info('Starting eval.') eval_results = self._evaluate(session, step) mlperf_log.resnet_print(key=mlperf_log.EVAL_STOP) mlperf_log.resnet_print( key=mlperf_log.EVAL_ACCURACY, value={ 'epoch': max(step // self._steps_per_epoch - 1, 0), 'value': float(eval_results[_EVAL_METRIC]) }) if eval_results[_EVAL_METRIC] >= self._stop_threshold: mlperf_log.resnet_print( key=mlperf_log.RUN_STOP, value={'success': 'true'}) else: mlperf_log.resnet_print( key=mlperf_log.RUN_STOP, value={'success': 'false'})
Example #15
Source File: serde.py From ngraph-python with Apache License 2.0 | 5 votes |
def assign_scalar(message, value): """ Adds the appropriate scalar type of value to the protobuf message """ if value is None: message.null_val = True elif isinstance(value, np.generic): assign_scalar(message, np.asscalar(value)) elif isinstance(value, (str, six.text_type)): message.string_val = value elif isinstance(value, np.dtype): message.dtype_val = dtype_to_protobuf(value) elif isinstance(value, float): message.double_val = value elif isinstance(value, bool): message.bool_val = value elif isinstance(value, six.integer_types): message.int_val = value elif isinstance(value, slice): slice_val = ops_pb.Slice() if value.start is not None: slice_val.start.value = value.start if value.step is not None: slice_val.step.value = value.step if value.stop is not None: slice_val.stop.value = value.stop message.slice_val.CopyFrom(slice_val) elif isinstance(value, dict): for key in value: assign_scalar(message.map_val.map[key], value[key]) # This encodes an empty dict for deserialization assign_scalar(message.map_val.map['_ngraph_map_sentinel_'], '') elif isinstance(value, Axis): message.axis.CopyFrom(axis_to_protobuf(value)) elif isinstance(value, AxesMap): message.axes_map.CopyFrom(axes_map_to_protobuf(value)) else: raise unhandled_scalar_value(value)
Example #16
Source File: dfun.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __rdiv__(self, other): # type: (Union[DiffFunction, float, int, np.multiarray.ndarray]) -> DiffFunction if isinstance(other, DiffFunction): return DivFunction(other, self) elif isinstance(other, float) or isinstance(other, int): return PwrFunction(self, -1.0, scale=other) elif isinstance(other, np.ndarray): return PwrFunction(self, -1.0, scale=np.asscalar(other)) else: raise NotImplementedError('Unknown type %s' % type(other))
Example #17
Source File: dfun.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __rsub__(self, other): # type: (Union[DiffFunction, float, int, np.multiarray.ndarray]) -> DiffFunction if isinstance(other, DiffFunction): return SumDiffFunction(other, self, f2_sgn=-1.0) elif isinstance(other, float) or isinstance(other, int): return ScaleAddFunction(self, other, -1.0) elif isinstance(other, np.ndarray): return ScaleAddFunction(self, np.asscalar(other), -1.0) else: raise NotImplementedError('Unknown type %s' % type(other))
Example #18
Source File: torch.py From mlcrate with MIT License | 5 votes |
def tonp(tensor): """Takes any PyTorch tensor and converts it to a numpy array or scalar as appropiate. When given something that isn't a PyTorch tensor, it will attempt to convert to a NumPy array or scalar anyway. Not heavily optimized.""" _check_torch_import() if isinstance(tensor, torch.Tensor): arr = tensor.data.detach().cpu().numpy() else: # It's not a tensor! We'll handle it anyway arr = np.array(tensor) if arr.shape == (): return np.asscalar(arr) else: return arr
Example #19
Source File: dfun.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __mul__(self, other): # type: (Union[DiffFunction, float, int, np.multiarray.ndarray]) -> DiffFunction if isinstance(other, DiffFunction): return ProdFunction(self, other) elif isinstance(other, float) or isinstance(other, int): return ScaleAddFunction(self, 0.0, other) elif isinstance(other, np.ndarray): return ScaleAddFunction(self, 0.0, np.asscalar(other)) else: raise NotImplementedError('Unknown type %s' % type(other))
Example #20
Source File: dfun.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __pow__(self, other): # type: (Union[float, int, np.multiarray.ndarray]) -> DiffFunction if isinstance(other, float) or isinstance(other, int): return PwrFunction(self, other, scale=1.0) elif isinstance(other, np.ndarray): return PwrFunction(self, np.asscalar(other), scale=1.0) else: raise NotImplementedError('Unknown type %s' % type(other))
Example #21
Source File: dfun.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __sub__(self, other): # type: (Union[DiffFunction, float, int, np.multiarray.ndarray]) -> DiffFunction if isinstance(other, DiffFunction): return SumDiffFunction(self, other, f2_sgn=-1.0) elif isinstance(other, float) or isinstance(other, int): return ScaleAddFunction(self, -other, 1.0) elif isinstance(other, np.ndarray): return ScaleAddFunction(self, -np.asscalar(other), 1.0) else: raise NotImplementedError('Unknown type %s' % type(other))
Example #22
Source File: in_memory_eval.py From training_results_v0.5 with Apache License 2.0 | 5 votes |
def after_run(self, run_context, run_values): # pylint: disable=unused-argument """Runs evaluator.""" step = np.asscalar(run_context.session.run(self._global_step_tensor)) if self._timer.should_trigger_for_step(step): logging.info('Starting eval.') eval_results = self._evaluate(run_context.session, step) mlperf_log.resnet_print(key=mlperf_log.EVAL_STOP) mlperf_log.resnet_print( key=mlperf_log.EVAL_ACCURACY, value={ 'epoch': max(step // self._steps_per_epoch - 1, 0), 'value': float(eval_results[_EVAL_METRIC]) }) # The ImageNet eval size is hard coded. mlperf_log.resnet_print(key=mlperf_log.EVAL_SIZE, value=50000) if eval_results[_EVAL_METRIC] >= self._stop_threshold: self._run_success = True mlperf_log.resnet_print( key=mlperf_log.RUN_STOP, value={'success': 'true'}) run_context.request_stop() if step // self._steps_per_epoch == self._eval_every_epoch_from: self._timer = training.SecondOrStepTimer( every_steps=self._steps_per_epoch) self._timer.reset()
Example #23
Source File: rfsm.py From pysheds with GNU General Public License v3.0 | 5 votes |
def node_full(self, node): # TODO: This should be generalized using recursion if node.vol == 0: full = np.array(True, dtype=bool) self.check_full(node, full) full = np.asscalar(full) return full return node.current_vol >= node.vol
Example #24
Source File: Baselines.py From defragTrees with MIT License | 5 votes |
def __parseTree(self, tree): m = len(tree.pred_) left = tree.left_ right = tree.right_ feature = tree.index_ threshold = tree.threshold_ value = tree.pred_ parent = [-1] * m ctype = [-1] * m for i in range(m): if not left[i] == -1: parent[left[i]] = i ctype[left[i]] = 0 if not right[i] == -1: parent[right[i]] = i ctype[right[i]] = 1 for i in range(m): if not left[i] == -1: continue subrule = [] c = ctype[i] idx = parent[i] while not idx == -1: subrule.append((int(feature[idx])+1, c, threshold[idx])) c = ctype[idx] idx = parent[idx] self.rule_.append(subrule) if np.array(value[i]).size > 1: self.pred_.append(np.argmax(np.array(value[i]))) else: self.pred_.append(np.asscalar(value[i]))
Example #25
Source File: Baselines.py From defragTrees with MIT License | 5 votes |
def __parseTree(self, mdl): t = mdl.tree_ m = len(t.value) left = t.children_left right = t.children_right feature = t.feature threshold = t.threshold value = t.value parent = [-1] * m ctype = [-1] * m for i in range(m): if not left[i] == -1: parent[left[i]] = i ctype[left[i]] = 0 if not right[i] == -1: parent[right[i]] = i ctype[right[i]] = 1 for i in range(m): if not left[i] == -1: continue subrule = [] c = ctype[i] idx = parent[i] while not idx == -1: subrule.append((int(feature[idx])+1, c, threshold[idx])) c = ctype[idx] idx = parent[idx] self.rule_.append(subrule) if np.array(value[i]).size > 1: self.pred_.append(np.argmax(np.array(value[i]))) else: self.pred_.append(np.asscalar(value[i])) #************************ # BTree Class #************************
Example #26
Source File: core.py From calfem-python with MIT License | 5 votes |
def bar3s(ex,ey,ez,ep,ed): """ Compute normal force in three dimensional bar element. :param list ex: element x coordinates [x1, x2] :param list ey: element y coordinates [y1, y2] :param list ez: element z coordinates [z1, z2] :param list ep: element properties [E, A], E - Young's modulus, A - Cross section area :param list ed: element displacements [u1, ..., u6] :return float N: normal force """ E = ep[0] A = ep[1] b = np.mat([ [ex[1]-ex[0]], [ey[1]-ey[0]], [ez[1]-ez[0]] ]) L = np.asscalar(np.sqrt(b.T*b)) n = np.asarray(b.T/L).reshape(3) G = np.mat([ [ n[0], n[1], n[2], 0. , 0. , 0. ], [ 0. , 0. , 0. , n[0], n[1], n[2]] ]) #Kle = E*A/L*np.mat([ # [ 1,-1], # [-1, 1] #]) u = np.asmatrix(ed).T N = E*A/L*np.mat([[-1.,1.]])*G*u return np.asscalar(N)
Example #27
Source File: core.py From calfem-python with MIT License | 5 votes |
def bar3e(ex,ey,ez,ep): """ Compute element stiffness matrix for three dimensional bar element. :param list ex: element x coordinates [x1, x2] :param list ey: element y coordinates [y1, y2] :param list ez: element z coordinates [z1, z2] :param list ep: element properties [E, A], E - Young's modulus, A - Cross section area :return mat Ke: stiffness matrix, [6 x 6] """ E = ep[0] A = ep[1] b = np.mat([ [ex[1]-ex[0]], [ey[1]-ey[0]], [ez[1]-ez[0]] ]) L = np.asscalar(np.sqrt(b.T*b)) n = np.asarray(b.T/L).reshape(3) G = np.mat([ [ n[0], n[1], n[2], 0., 0., 0. ], [ 0., 0., 0., n[0], n[1], n[2]] ]) Kle = E*A/L*np.mat([ [ 1,-1], [-1, 1] ]) return G.T*Kle*G
Example #28
Source File: core.py From calfem-python with MIT License | 5 votes |
def bar2s(ex,ey,ep,ed): """ Compute normal force in two dimensional bar element. :param list ex: element x coordinates [x1, x2] :param list ey: element y coordinates [y1, y2] :param list ep: element properties [E, A], E - Young's modulus, A - Cross section area :param list ed: element displacements [u1, u2, u3, u4] :return float N: element foce [N] """ E=ep[0] A=ep[1] b = np.mat([[ex[1]-ex[0]],[ey[1]-ey[0]]]) L = np.asscalar(np.sqrt(b.T*b)) #Kle = np.mat([[1.,-1.],[-1.,1.]])*E*A/L n = np.asarray(b.T/L).reshape(2,) G = np.mat([ [n[0],n[1],0.,0.], [0.,0.,n[0],n[1]] ]) u=np.asmatrix(ed).T N=E*A/L*np.mat([[-1.,1.]])*G*u return np.asscalar(N)
Example #29
Source File: tensor_util.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def SlowAppendBoolArrayToTensorProto(tensor_proto, proto_values): tensor_proto.bool_val.extend([np.asscalar(x) for x in proto_values])
Example #30
Source File: tensor_util.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def SlowAppendComplex64ArrayToTensorProto(tensor_proto, proto_values): tensor_proto.scomplex_val.extend([np.asscalar(v) for x in proto_values for v in [x.real, x.imag]])