本文整理汇总了Python中numpy.atleast_2d方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.atleast_2d方法的具体用法?Python numpy.atleast_2d怎么用?Python numpy.atleast_2d使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.atleast_2d方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: kernel_matrix_xX
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例2: invertFast
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例3: pop_from_array_or_individual
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例4: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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)
示例5: makeadmask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例6: _move_point
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例7: apply_to_solution
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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)
示例8: test_bb_full
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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)
示例9: grad_dot
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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))
示例10: predict_log_proba
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例11: sparse_to_dense
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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
示例12: to_native_types
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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)
示例13: fit_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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_
示例14: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
def __init__(self, dataset):
self.dataset = atleast_2d(dataset)
if not self.dataset.size > 1:
raise ValueError("`dataset` input should have multiple elements.")
self.d, self.n = self.dataset.shape
self._compute_covariance()
示例15: evaluate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import atleast_2d [as 别名]
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