本文整理汇总了Python中numpy.vectorize方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.vectorize方法的具体用法?Python numpy.vectorize怎么用?Python numpy.vectorize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.vectorize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_static_nonlinearity
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def test_static_nonlinearity(self):
# Linear dynamical system
linsys = self.siso_linsys
ioslin = ios.LinearIOSystem(linsys)
# Nonlinear saturation
sat = lambda u: u if abs(u) < 1 else np.sign(u)
sat_output = lambda t, x, u, params: sat(u)
nlsat = ios.NonlinearIOSystem(None, sat_output, inputs=1, outputs=1)
# Set up parameters for simulation
T, U, X0 = self.T, 2 * self.U, self.X0
Usat = np.vectorize(sat)(U)
# Make sure saturation works properly by comparing linear system with
# saturated input to nonlinear system with saturation composition
lti_t, lti_y, lti_x = ct.forced_response(linsys, T, Usat, X0)
ios_t, ios_y, ios_x = ios.input_output_response(
ioslin * nlsat, T, U, X0, return_x=True)
np.testing.assert_array_almost_equal(lti_t, ios_t)
np.testing.assert_array_almost_equal(lti_y, ios_y, decimal=2)
示例2: test_keywords2_ticket_2100
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def test_keywords2_ticket_2100(self):
# Test kwarg support: enhancement ticket 2100
def foo(a, b=1):
return a + b
f = vectorize(foo)
args = np.array([1, 2, 3])
r1 = f(a=args)
r2 = np.array([2, 3, 4])
assert_array_equal(r1, r2)
r1 = f(b=1, a=args)
assert_array_equal(r1, r2)
r1 = f(args, b=2)
r2 = np.array([3, 4, 5])
assert_array_equal(r1, r2)
示例3: dict_lookup
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def dict_lookup(dict_, keys, default=None):
"""Looks up :attr:`keys` in the dict, returns the corresponding values.
The :attr:`default` is used for keys not present in the dict.
Args:
dict_ (dict): A dictionary for lookup.
keys: A numpy array or a (possibly nested) list of keys.
default (optional): Value to be returned when a key is not in
:attr:`dict_`. Error is raised if :attr:`default` is not given and
key is not in the dict.
Returns:
A numpy array of values with the same structure as :attr:`keys`.
Raises:
TypeError: If key is not in :attr:`dict_` and :attr:`default` is `None`.
"""
return np.vectorize(lambda x: dict_.get(x, default))(keys)
示例4: xindex
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def xindex(array, row_num, col_num=None, area_num=1):
is_reference = isinstance(array, Ranges)
if is_reference:
arrays = [Ranges((rng,), array.values).value for rng in array.ranges]
else:
arrays = [array]
row_num, col_num, area_num = parse_ranges(row_num, col_num, area_num)[0]
res = np.vectorize(_index, excluded={0}, otypes=[object])(
arrays, row_num, col_num, area_num, is_reference,
isinstance(row_num, np.ndarray)
)
if not res.shape:
res = res.reshape(1, 1)
return res.view(Array)
示例5: testRelativePositionalEmbeddingLayer
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def testRelativePositionalEmbeddingLayer(self):
with self.session(use_gpu=False):
radius = 3
p = layers.RelativePositionalEmbeddingLayer.Params().Set(
name='rel_position_emb', radius=radius, dim=4)
layer = p.Instantiate()
indices = np.array([-5, -2, 0, 1, 4], dtype=np.int32)
pos_emb = layer.FPropDefaultTheta(tf.convert_to_tensor(indices))
self.evaluate(tf.global_variables_initializer())
actual_pos_emb, full_emb = self.evaluate([pos_emb, layer.vars.w])
clipped_indices = np.vectorize(lambda x: max(-radius, min(radius, x)))(
indices) + radius
expected_output = np.take_along_axis(full_emb,
np.expand_dims(clipped_indices, -1),
0)
print('expected_position_embs:', expected_output)
print('actual_position_embs:', actual_pos_emb)
self.assertAllClose(actual_pos_emb, expected_output)
示例6: plot3d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def plot3d(self, scale=0.32):
r"""Plot 3d scatter plot of benchmark function.
Args:
scale (float): Scale factor for points.
"""
fig = plt.figure()
ax = Axes3D(fig)
func = self.function()
Xr, Yr = arange(self.Lower, self.Upper, scale), arange(self.Lower, self.Upper, scale)
X, Y = meshgrid(Xr, Yr)
Z = vectorize(self.__2dfun)(X, Y, func)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
ax.contourf(X, Y, Z, zdir='z', offset=-10, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
示例7: make_polynomial
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def make_polynomial(degree=3, n_samples=100, bias=0.0, noise=0.0,
return_coefs=False, random_state=None):
"""
Generate a noisy polynomial for a regression problem
Examples
--------
>>> X, y, coefs = make_polynomial(degree=3, n_samples=200, noise=.5,
... return_coefs=True, random_state=1)
"""
generator = check_random_state(random_state)
# TODO: Add arguments to support other priors
coefs = generator.randn(degree + 1)
pows = np.arange(degree + 1)
poly = np.vectorize(lambda x: np.sum(coefs * x ** pows))
X, y = make_regression(poly, n_samples=n_samples, bias=bias, noise=noise,
random_state=random_state)
if return_coefs:
return X, y, coefs
return X, y
示例8: _munp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def _munp(self, n, beta, m):
"""
Returns the n-th non-central moment of the crystalball function.
"""
N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta))
def n_th_moment(n, beta, m):
"""
Returns n-th moment. Defined only if n+1 < m
Function cannot broadcast due to the loop over n
"""
A = (m/beta)**m * np.exp(-beta**2 / 2.0)
B = m/beta - beta
rhs = 2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))
lhs = np.zeros(rhs.shape)
for k in range(n + 1):
lhs += sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)
return A * lhs + rhs
return N * _lazywhere(np.atleast_1d(n + 1 < m),
(n, beta, m),
np.vectorize(n_th_moment, otypes=[np.float]),
np.inf)
示例9: get_forces
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def get_forces(self):
# Return the force vector for the problem
topx_to_id = np.vectorize(
lambda x: xy_to_id(x, 0, self.nelx, self.nely))
topx = 2 * topx_to_id(np.arange((self.nelx + 1) // 2)) + 1
f = np.zeros((2 * (self.nelx + 1) * (self.nely + 1), 1))
f[topx, 0] = -100
return f
示例10: get_fixed_nodes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def get_fixed_nodes(self):
""" Return a list of fixed nodes for the problem. """
x = np.arange(self.passive_min_x)
topx_to_id = np.vectorize(
lambda x: xy_to_id(x, 0, self.nelx, self.nely))
ids = topx_to_id(x)
fixed = np.union1d(2 * ids, 2 * ids + 1)
return fixed
示例11: get_passive_elements
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def get_passive_elements(self):
X, Y = np.mgrid[self.passive_min_x:self.passive_max_x + 1,
self.passive_min_y:self.passive_max_y]
pairs = np.vstack([X.ravel(), Y.ravel()]).T
passive_to_ids = np.vectorize(lambda pair: xy_to_id(*pair,
nelx=self.nelx - 1, nely=self.nely - 1), signature="(m)->()")
return passive_to_ids(pairs)
示例12: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def __getitem__(self, index):
raw_data = np.fromfile(self.im_idx[index], dtype=np.float32).reshape((-1, 4))
if self.imageset == 'test':
annotated_data = np.expand_dims(np.zeros_like(raw_data[:,0],dtype=int),axis=1)
else:
annotated_data = np.fromfile(self.im_idx[index].replace('velodyne','labels')[:-3]+'label', dtype=np.int32).reshape((-1,1))
annotated_data = annotated_data & 0xFFFF #delete high 16 digits binary
annotated_data = np.vectorize(self.learning_map.__getitem__)(annotated_data)
data_tuple = (raw_data[:,:3], annotated_data.astype(np.uint8))
if self.return_ref:
data_tuple += (raw_data[:,3],)
return data_tuple
示例13: getTransform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def getTransform(img, pc, s, m_p, mean_m):
z = np.copy(img)
p, m = getLandmarks(img, pc, m_p)
#using img, p, m, s, mean_m get the normalized image
p_1, p_2 = p[0], p[1]
s_1, s_2 = s[0], s[1]
#histogram values at locations (pc + landmarks)
m = [p_1] + list(m) + [p_2]
#map scale corresponding to these values
mean_m = [s_1] + list(mean_m) + [s_2]
new_img = np.zeros_like(img, dtype=np.int64)
hist_indices = np.zeros_like(img, dtype=np.int64)
hist_indices = np.copy(new_img)
for m_ in m:
hist_indices += (img > m_).astype(int)
hist_indices = np.clip(hist_indices, 1, len(m) - 1, out=hist_indices)
indexer_m = lambda v: m[v]
indexer_mm = lambda v: mean_m[v]
f_m = np.vectorize(indexer_m)
f_mm = np.vectorize(indexer_mm)
new_p_1 = f_m(hist_indices - 1)
new_p_2 = f_m(hist_indices)
new_s_1 = f_mm(hist_indices - 1)
new_s_2 = f_mm(hist_indices)
new_img = mapLandmarksVec([new_p_1, new_p_2], [new_s_1, new_s_2], img)
new_img = np.clip(new_img, s_1-1, s_2+1, out=new_img)
return new_img
##################################################################
示例14: calc_EVPOC
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def calc_EVPOC(self):
Comp = self.Completeness
bins = 1000
# xedges is array of separation values for interpolant
xedges = np.linspace(0., Comp.PlanetPopulation.rrange[1].value, bins)*\
Comp.PlanetPopulation.arange.unit
xedges = xedges.to('AU').value
# yedges is array of delta magnitude values for interpolant
ymin = np.round(-2.5*np.log10(float(Comp.PlanetPopulation.prange[1]*\
Comp.PlanetPopulation.Rprange[1]/Comp.PlanetPopulation.rrange[0])**2))
ymax = np.round(-2.5*np.log10(float(Comp.PlanetPopulation.prange[0]*\
Comp.PlanetPopulation.Rprange[0]/Comp.PlanetPopulation.rrange[1])**2*1e-11))
yedges = np.linspace(ymin, ymax, bins)
# number of planets for each Monte Carlo simulation
nplan = int(np.min([1e6,Comp.Nplanets]))
# number of simulations to perform (must be integer)
steps = int(Comp.Nplanets/nplan)
Cpath = os.path.join(Comp.classpath, Comp.filename+'.comp')
H, xedges, yedges = self.genC(Cpath, nplan, xedges, yedges, steps)
EVPOCpdf = interpolate.RectBivariateSpline(xedges, yedges, H.T)
EVPOC = np.vectorize(EVPOCpdf.integral)
self.EVPOC = EVPOC
示例15: predict_proba
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import vectorize [as 别名]
def predict_proba(self, X):
f = np.vectorize(self._platt_func)
raw_predictions = self.decision_function(X)
platt_predictions = f(raw_predictions).reshape(-1, 1)
prob_positive = platt_predictions / platt_predictions.sum(axis=1)[:, None]
prob_negative = 1.0 - prob_positive
probabilities = np.hstack([prob_negative, prob_positive])
return probabilities