Python numpy.atleast_2d() Examples
The following are 30
code examples of numpy.atleast_2d().
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: test_optimization_methods.py From simnibs with GNU General Public License v3.0 | 6 votes |
def test_bb_full(self, optimization_variables_avg): l, Q, A = optimization_variables_avg m = 2e-3 m1 = 4e-3 f = 1e-2 max_active = 2 init = optimization_methods.bb_state([], [], list(range(len(l)))) bf = functools.partial( optimization_methods._bb_bounds_function, np.atleast_2d(l), Q, f, m1, m, max_active) final_state = optimization_methods._branch_and_bound( init, bf, 1e-2, 100) x = final_state.x_lb assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4 assert np.linalg.norm(x, 0) <= max_active assert np.all(np.abs(x) <= m + 1e-4) assert np.isclose(np.sum(x), 0) assert np.isclose(l.dot(x), f)
Example #2
Source File: so_gradient_descent.py From pymoo with Apache License 2.0 | 6 votes |
def __init__(self, X, dX=None, objective=0, display=SingleObjectiveDisplay(), **kwargs) -> None: super().__init__(display=display, **kwargs) self.objective = objective self.n_restarts = 0 self.default_termination = SingleObjectiveDefaultTermination() self.X, self.dX = X, dX self.F, self.CV = None, None if self.X.ndim == 1: self.X = np.atleast_2d(X)
Example #3
Source File: population.py From pymoo with Apache License 2.0 | 6 votes |
def pop_from_array_or_individual(array, pop=None): # the population type can be different - (different type of individuals) if pop is None: pop = Population() # provide a whole population object - (individuals might be already evaluated) if isinstance(array, Population): pop = array elif isinstance(array, np.ndarray): pop = pop.new("X", np.atleast_2d(array)) elif isinstance(array, Individual): pop = Population(1) pop[0] = array else: return None return pop
Example #4
Source File: nb_sklearn.py From recordlinkage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def predict_log_proba(self, X): """ Return log-probability estimates for the test vector X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array-like, shape = [n_samples, n_classes] Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute `classes_`. """ jll = self._joint_log_likelihood(X) # normalize by P(x) = P(f_1, ..., f_n) log_prob_x = logsumexp(jll, axis=1) # return shape = (2,) return jll - np.atleast_2d(log_prob_x).T
Example #5
Source File: utils.py From tangent with Apache License 2.0 | 6 votes |
def grad_dot(dy, x1, x2): """Gradient of NumPy dot product w.r.t. to the left hand side. Args: dy: The gradient with respect to the output. x1: The left hand side of the `numpy.dot` function. x2: The right hand side Returns: The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the broadcasting involved. """ if len(numpy.shape(x1)) == 1: dy = numpy.atleast_2d(dy) elif len(numpy.shape(x2)) == 1: dy = numpy.transpose(numpy.atleast_2d(dy)) x2 = numpy.transpose(numpy.atleast_2d(x2)) x2_t = numpy.transpose(numpy.atleast_2d( numpy.sum(x2, axis=tuple(numpy.arange(numpy.ndim(x2) - 2))))) dy_x2 = numpy.sum(dy, axis=tuple(-numpy.arange(numpy.ndim(x2) - 2) - 2)) return numpy.reshape(numpy.dot(dy_x2, x2_t), numpy.shape(x1))
Example #6
Source File: tedana.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def makeadmask(cdat,min=True,getsum=False): nx,ny,nz,Ne,nt = cdat.shape mask = np.ones((nx,ny,nz),dtype=np.bool) if min: mask = cdat[:,:,:,:,:].prod(axis=-1).prod(-1)!=0 return mask else: #Make a map of longest echo that a voxel can be sampled with, #with minimum value of map as X value of voxel that has median #value in the 1st echo. N.b. larger factor leads to bias to lower TEs emeans = cdat[:,:,:,:,:].mean(-1) medv = emeans[:,:,:,0] == stats.scoreatpercentile(emeans[:,:,:,0][emeans[:,:,:,0]!=0],33,interpolation_method='higher') lthrs = np.squeeze(np.array([ emeans[:,:,:,ee][medv]/3 for ee in range(Ne) ])) if len(lthrs.shape)==1: lthrs = np.atleast_2d(lthrs).T lthrs = lthrs[:,lthrs.sum(0).argmax()] mthr = np.ones([nx,ny,nz,ne]) for ee in range(Ne): mthr[:,:,:,ee]*=lthrs[ee] mthr = np.abs(emeans[:,:,:,:])>mthr masksum = np.array(mthr,dtype=np.int).sum(-1) mask = masksum!=0 if getsum: return mask,masksum else: return mask
Example #7
Source File: ZIFA.py From ZIFA with MIT License | 6 votes |
def invertFast(A, d): """ given an array A of shape d x k and a d x 1 vector d, computes (A * A.T + diag(d)) ^{-1} Checked. """ assert(A.shape[0] == d.shape[0]) assert(d.shape[1] == 1) k = A.shape[1] A = np.array(A) d_vec = np.array(d) d_inv = np.array(1 / d_vec[:, 0]) inv_d_squared = np.dot(np.atleast_2d(d_inv).T, np.atleast_2d(d_inv)) M = np.diag(d_inv) - inv_d_squared * np.dot(np.dot(A, np.linalg.inv(np.eye(k, k) + np.dot(A.T, mult_diag(d_inv, A)))), A.T) return M
Example #8
Source File: binvox_rw.py From 3D-R2N2 with MIT License | 6 votes |
def sparse_to_dense(voxel_data, dims, dtype=np.bool): if voxel_data.ndim != 2 or voxel_data.shape[0] != 3: raise ValueError('voxel_data is wrong shape; should be 3xN array.') if np.isscalar(dims): dims = [dims] * 3 dims = np.atleast_2d(dims).T # truncate to integers xyz = voxel_data.astype(np.int) # discard voxels that fall outside dims valid_ix = ~np.any((xyz < 0) | (xyz >= dims), 0) xyz = xyz[:, valid_ix] out = np.zeros(dims.flatten(), dtype=dtype) out[tuple(xyz)] = True return out # def get_linear_index(x, y, z, dims): # """ Assuming xzy order. (y increasing fastest. # TODO ensure this is right when dims are not all same # """ # return x*(dims[1]*dims[2]) + z*dims[1] + y
Example #9
Source File: Utility.py From fuku-ml with MIT License | 6 votes |
def kernel_matrix_xX(svm_model, original_x, original_X): if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'): K = (svm_model.zeta + svm_model.gamma * np.dot(original_x, original_X.T)) ** svm_model.Q elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'): K = np.exp(-svm_model.gamma * (cdist(original_X, np.atleast_2d(original_x), 'euclidean').T ** 2)).ravel() ''' K = np.zeros((svm_model.data_num, svm_model.data_num)) for i in range(svm_model.data_num): for j in range(svm_model.data_num): if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'): K[i, j] = Kernel.polynomial_kernel(svm_model, original_x, original_X[j]) elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'): K[i, j] = Kernel.gaussian_kernel(svm_model, original_x, original_X[j]) ''' return K
Example #10
Source File: blocks.py From recruit with Apache License 2.0 | 6 votes |
def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view('i8') if slicer is not None: i8values = i8values[..., slicer] from pandas.io.formats.format import _get_format_datetime64_from_values fmt = _get_format_datetime64_from_values(values, date_format) result = tslib.format_array_from_datetime( i8values.ravel(), tz=getattr(self.values, 'tz', None), format=fmt, na_rep=na_rep).reshape(i8values.shape) return np.atleast_2d(result)
Example #11
Source File: electrode_placement.py From simnibs with GNU General Public License v3.0 | 6 votes |
def _move_point(new_position, to_be_moved, nodes, triangles, min_angle=0.25, edge_list=None, kdtree=None): '''Moves one point to the new_position. The angle of the patch should not become less than min_angle (in radians) ''' # Certify that the new_position is inside the patch tr = _triangle_with_points(np.atleast_2d(new_position), triangles, nodes, edge_list=edge_list, kdtree=kdtree) tr_with_node = np.where(np.any(triangles == to_be_moved, axis=1))[0] patch = triangles[tr_with_node] if not np.in1d(tr, tr_with_node): return None, None new_nodes = np.copy(nodes) position = nodes[to_be_moved] d = new_position - position # Start from the full move and go back for t in np.linspace(0, 1, num=10)[::-1]: new_nodes[to_be_moved] = position + t*d angle = np.min(_calc_triangle_angles(new_nodes[patch])) if angle > min_angle: break # Return the new node list and the minimum angle in the patch return new_nodes, angle
Example #12
Source File: onlineLDA.py From IDEA with MIT License | 6 votes |
def fit_transform(self, X, y=None): """Apply dimensionality reduction on X Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. Sparse matrix allowed. Returns ------- doc_topic : array-like, shape (n_samples, n_topics) Point estimate of the document-topic distributions """ if isinstance(X, np.ndarray): # in case user passes a (non-sparse) array of shape (n_features,) # turn it into an array of shape (1, n_features) X = np.atleast_2d(X) self._fit(X) return self.doc_topic_
Example #13
Source File: fem.py From simnibs with GNU General Public License v3.0 | 6 votes |
def apply_to_solution(self, x, dof_map): ''' Applies the dirichlet BC to a solution Parameters: ------- x: numpy array Righ-hand side dof_map: dofMap Mapping of node indexes to rows and columns in A and b Returns: ------ x: numpy array Righ-hand side, modified dof_map: dofMap Mapping of node indexes to rows and columns in A and b, modified ''' if np.any(np.in1d(self.nodes, dof_map.inverse)): raise ValueError('Found DOFs already defined') dof_inverse = np.hstack((dof_map.inverse, self.nodes)) x = np.atleast_2d(x) if x.shape[0] < x.shape[1]: x = x.T x = np.vstack((x, np.tile(self.values, (x.shape[1], 1)).T)) return x, dofMap(dof_inverse)
Example #14
Source File: test_missing.py From recruit with Apache License 2.0 | 5 votes |
def _check_behavior(self, arr, expected): for method in TestNAObj._1d_methods: result = getattr(libmissing, method)(arr) tm.assert_numpy_array_equal(result, expected) arr = np.atleast_2d(arr) expected = np.atleast_2d(expected) for method in TestNAObj._2d_methods: result = getattr(libmissing, method)(arr) tm.assert_numpy_array_equal(result, expected)
Example #15
Source File: seriesnet.py From seriesnet with MIT License | 5 votes |
def evaluate_timeseries(timeseries, predict_size): # timeseries input is 1-D numpy array # forecast_size is the forecast horizon timeseries = timeseries[~pd.isna(timeseries)] length = len(timeseries)-1 timeseries = np.atleast_2d(np.asarray(timeseries)) if timeseries.shape[0] == 1: timeseries = timeseries.T model = DC_CNN_Model(length) print('\n\nModel with input size {}, output size {}'. format(model.input_shape, model.output_shape)) model.summary() X = timeseries[:-1].reshape(1,length,1) y = timeseries[1:].reshape(1,length,1) model.fit(X, y, epochs=3000) pred_array = np.zeros(predict_size).reshape(1,predict_size,1) X_test_initial = timeseries[1:].reshape(1,length,1) #pred_array = model.predict(X_test_initial) if predictions of training samples required #forecast is created by predicting next future value based on previous predictions pred_array[:,0,:] = model.predict(X_test_initial)[:,-1:,:] for i in range(predict_size-1): pred_array[:,i+1:,:] = model.predict(np.append(X_test_initial[:,i+1:,:], pred_array[:,:i+1,:]).reshape(1,length,1))[:,-1:,:] return pred_array.flatten()
Example #16
Source File: test_linalg.py From recruit with Apache License 2.0 | 5 votes |
def test_empty(self): assert_equal(norm([]), 0.0) assert_equal(norm(array([], dtype=self.dt)), 0.0) assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
Example #17
Source File: concat.py From recruit with Apache License 2.0 | 5 votes |
def _concatenate_2d(to_concat, axis): # coerce to 2d if needed & concatenate if axis == 1: to_concat = [np.atleast_2d(x) for x in to_concat] return np.concatenate(to_concat, axis=axis)
Example #18
Source File: blocks.py From recruit with Apache License 2.0 | 5 votes |
def concat_same_type(self, to_concat, placement=None): # need to handle concat([tz1, tz2]) here, since DatetimeArray # only handles cases where all the tzs are the same. # Instead of placing the condition here, it could also go into the # is_uniform_join_units check, but I'm not sure what is better. if len({x.dtype for x in to_concat}) > 1: values = _concat._concat_datetime([x.values for x in to_concat]) placement = placement or slice(0, len(values), 1) if self.ndim > 1: values = np.atleast_2d(values) return ObjectBlock(values, ndim=self.ndim, placement=placement) return super(DatetimeTZBlock, self).concat_same_type(to_concat, placement)
Example #19
Source File: toy2d_intractable.py From zhusuan with MIT License | 5 votes |
def plot_isocontours(ax, func, xlimits, ylimits, numticks=101): x = np.linspace(*xlimits, num=numticks) y = np.linspace(*ylimits, num=numticks) xx, yy = np.meshgrid(x, y) z = func(np.concatenate([np.atleast_2d(xx.ravel()), np.atleast_2d(yy.ravel())]).T) z = z.reshape(xx.shape) ax.contour(xx, yy, z)
Example #20
Source File: classifiers.py From recordlinkage with BSD 3-Clause "New" or "Revised" License | 5 votes |
def intercept(self, value): if value is not None: value = numpy.asarray(value) value = numpy.atleast_2d(value) self.kernel.intercept_ = value else: try: del self.kernel.intercept_ except AttributeError: pass
Example #21
Source File: opt_struct.py From simnibs with GNU General Public License v3.0 | 5 votes |
def _find_directions(mesh, lf_type, directions, indexes, mapping=None): if directions == 'normal': if 4 in np.unique(mesh.elm.elm_type): raise ValueError("Can't define a normal direction for volumetric data!") if lf_type == 'node': directions = -mesh.nodes_normals()[indexes] elif lf_type == 'element': directions = -mesh.triangle_normals()[indexes] return directions else: directions = np.atleast_2d(directions) if directions.shape[1] != 3: raise ValueError( "directions must be the string 'normal' or a Nx3 array" ) if mapping is None: if len(directions) == len(indexes): mapping = np.arange(len(indexes)) else: raise ValueError('Different number of indexes and directions and no ' 'mapping defined') elif len(directions) == 1: mapping = np.zeros(len(indexes), dtype=int) directions = directions/np.linalg.norm(directions, axis=1)[:, None] return directions[mapping]
Example #22
Source File: tangents.py From tangent with Apache License 2.0 | 5 votes |
def tatleast_2d(z, x): d[z] = numpy.atleast_2d(d[x])
Example #23
Source File: grads.py From tangent with Apache License 2.0 | 5 votes |
def atleast_2d(y, x): d[x] = numpy.reshape(d[y], numpy.shape(x))
Example #24
Source File: get_fields_at_coordinates.py From simnibs with GNU General Public License v3.0 | 5 votes |
def main(): args = parse_arguments(sys.argv[1:]) msh = mesh_io.read_msh(os.path.abspath(os.path.realpath(os.path.expanduser(args.mesh)))) fn_csv = os.path.expanduser(args.csv) if args.l is not None: labels = [int(n) for n in args.l[0].split(',')] msh = msh.crop_mesh(tags=labels) points = np.atleast_2d(np.loadtxt(fn_csv, delimiter=',', dtype=float)) if points.shape[1] != 3: raise IOError('CSV file should have 3 columns') csv_basename, _ = os.path.splitext(fn_csv) for ed in msh.elmdata: fn_out = '{0}_{1}.csv'.format(csv_basename, ed.field_name) logger.info('Interpolating field: {0} and writing to file: {1}'.format( ed.field_name, fn_out)) f = ed.interpolate_scattered( points, out_fill=args.out_fill, method=args.method, continuous=False, squeeze=False) if f.ndim == 1: f = f[:, None] np.savetxt(fn_out, f, delimiter=',') for nd in msh.nodedata: fn_out = '{0}_{1}.csv'.format(csv_basename, nd.field_name) logger.info('Interpolating field: {0} and writing to file: {1}'.format( nd.field_name, fn_out)) f = nd.interpolate_scattered( points, out_fill=args.out_fill, squeeze=False) if f.ndim == 1: f = f[:, None] np.savetxt(fn_out, f, delimiter=',')
Example #25
Source File: test_opt_struct.py From simnibs with GNU General Public License v3.0 | 5 votes |
def test_find_indexes_pos_elm(self, tissues, pos, sphere_surf, r): index, mapping = opt_struct._find_indexes( sphere_surf, 'element', positions=pos, radius=r, tissues=tissues) if tissues is None: elm_with_tag = sphere_surf.elm.elm_number else: elm_with_tag = sphere_surf.elm.elm_number[np.isin(sphere_surf.elm.tag1, tissues)] elms = sphere_surf.elements_baricenters()[elm_with_tag] roi = [] mp = [] pos = np.atleast_2d(pos) for i, p in enumerate(pos): dist = np.linalg.norm(p - elms, axis=1) idx_nearest = elm_with_tag[np.argmin(dist)] if r > 0: center = elms[np.argmin(dist)] dist_center = np.linalg.norm(center - elms, axis=1) n_roi = np.sum(dist_center <= r) roi.extend(elm_with_tag[dist_center <= r]) else: n_roi = 1 roi.append(idx_nearest) mp.extend(n_roi*(i,)) assert np.all(np.sort(index) == np.sort(roi)) assert np.all(np.sort(mapping) == np.sort(mp))
Example #26
Source File: test_opt_struct.py From simnibs with GNU General Public License v3.0 | 5 votes |
def test_find_indexes_pos_node(self, tissues, pos, sphere_surf, r): index, mapping = opt_struct._find_indexes( sphere_surf, 'node', positions=pos, radius=r, tissues=tissues) if tissues is None: nodes_with_tag = sphere_surf.nodes.node_number else: nodes_with_tag = sphere_surf.elm.nodes_with_tag(tissues) nodes = sphere_surf.nodes[nodes_with_tag] roi = [] mp = [] pos = np.atleast_2d(pos) for i, p in enumerate(pos): dist = np.linalg.norm(p - nodes, axis=1) idx_nearest = nodes_with_tag[np.argmin(dist)] if r > 0: center = nodes[np.argmin(dist)] dist_center = np.linalg.norm(center - nodes, axis=1) n_roi = np.sum(dist_center <= r) roi.extend(nodes_with_tag[dist_center <= r]) else: n_roi = 1 roi.append(idx_nearest) mp.extend(n_roi*(i,)) assert np.all(np.sort(index) == np.sort(roi)) assert np.all(np.sort(mapping) == np.sort(mp))
Example #27
Source File: test_optimization_methods.py From simnibs with GNU General Public License v3.0 | 5 votes |
def test_bb_upper_bound(self, optimization_variables_avg): l, Q, A = optimization_variables_avg m = 2e-3 m1 = 4e-3 f = 1e-3 max_active = 2 state = optimization_methods.bb_state([1], [2], [3, 0, 4]) x_ub, ub = optimization_methods._bb_upper_bound( np.atleast_2d(l), Q, f, m1, m, max_active, state) assert np.linalg.norm(x_ub, 1) <= 2 * m1 + 1e-4 assert np.all(np.abs(x_ub) <= m + 1e-4) assert np.isclose(np.sum(x_ub), 0) assert np.isclose(x_ub[state.inactive], 0) assert np.isclose(l.dot(x_ub), f)
Example #28
Source File: optimization_methods.py From simnibs with GNU General Public License v3.0 | 5 votes |
def _constrained_l0_branch_and_bound( l, Q, target_mean, max_total_current, max_el_current, max_l0, eps_bb=1e-1, max_bb_iter=100, start_inactive=[], start_active=[], log_level=20): ''' Solves the constrained L0 problem using a branch-and-bound algorithm ''' logger.log(log_level, "Starting BB") max_l0 = int(max_l0) l = copy.copy(np.atleast_2d(l)) if max_total_current is None and max_el_current is None: raise ValueError('at least one of max_l1 or max_el_current must not be None') if max_el_current is not None: if max_total_current is not None: max_total_current = min(max_total_current, max_l0 * max_el_current / 2.) else: max_total_current = max_l0 * max_el_current else: max_el_current = max_total_current n = l.shape[1] # Define the initial state if len(start_inactive) > 0: assert min(start_inactive) >= 0 and max(start_inactive) < n, \ 'Invalid electrode number in start_inactive' if len(start_active) > 0: assert min(start_active) >= 0 and max(start_active) < n, \ 'Invalid electrode number in start_active' unassigned = [i for i in range(n) if i not in start_inactive + start_active] init = bb_state(start_active, start_inactive, unassigned) # partilize _bb_bounds_function bf = functools.partial( _bb_bounds_function, l, Q, target_mean, max_total_current, max_el_current, max_l0) # do the branch and bound final_state = _branch_and_bound(init, bf, eps_bb, max_bb_iter, log_level=log_level) x = final_state.x_ub return x
Example #29
Source File: optimization_methods.py From simnibs with GNU General Public License v3.0 | 5 votes |
def optimize_field_component(l, max_total_current=None, max_el_current=None): ''' Optimize the intensity of the field in the given direction without regard to focality Parameters ------------ l: np.ndarray Linear objective, obtained from target_matrices. If "l" is muti-targeted, optimizes the average of the targets max_total_current: float (optional) Maximal current flow though all electrodes. Default: No maximum max_el_current: float (optional) Maximal current flow though each electrode. Default: No maximum Returns -------- x: np.ndarray Optimal electrode currents ''' if max_total_current is None and max_el_current is None: raise ValueError('Please define a maximal total current or maximal electrode ' + 'current') l = np.average(np.atleast_2d(l), axis=0) n = l.shape[0] if max_total_current is not None: A_ub = np.ones((1, 2 * n)) b_ub = np.array([2 * max_total_current]) else: A_ub = None b_ub = None l_ = np.hstack([l, -l]) A_eq = np.hstack([np.ones((1, n)), -np.ones((1, n))]) b_eq = np.array([0.]) sol = scipy.optimize.linprog(-l_, A_ub, b_ub, A_eq, b_eq, bounds=(0, max_el_current)) x_ = sol.x return x_[:n] - x_[n:]
Example #30
Source File: kde.py From svviz with MIT License | 5 votes |
def evaluate(self, points): points = atleast_2d(points) d, m = points.shape if d != self.d: if d == 1 and m == self.d: # points was passed in as a row vector points = reshape(points, (self.d, 1)) m = 1 else: msg = "points have dimension %s, dataset has dimension %s" % (d, self.d) raise ValueError(msg) result = zeros((m,), dtype=np.float) if m >= self.n: # there are more points than data, so loop over data for i in range(self.n): diff = self.dataset[:, i, newaxis] - points tdiff = dot(self.inv_cov, diff) energy = sum(diff*tdiff,axis=0) / 2.0 result = result + exp(-energy) else: # loop over points for i in range(m): diff = self.dataset - points[:, i, newaxis] tdiff = dot(self.inv_cov, diff) energy = sum(diff * tdiff, axis=0) / 2.0 result[i] = sum(exp(-energy), axis=0) result = result / self._norm_factor return result